This commit is contained in:
vfs committed 2026-04-28 19:46:06 +02:00
1 parent 173c01b01b
commit 5772a7d855
22 files changed
+731 -149

No files matched your search

+20 -1
View File
@@ -11,7 +11,10 @@ import (
"strconv"
"party.at/party/internal/validator"
"github.com/julienschmidt/httprouter"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"crypto/rand"
)
type envelope map[string]interface{}
@@ -191,3 +194,19 @@ func (app *application) background(fn func()) {
fn()
}()
}
func GenerateIssueKey() ([]byte, int, []byte, error) {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, 0, nil, err
}
// Encode private key as PEM
privDER := x509.MarshalPKCS1PrivateKey(key)
privPEM := pem.EncodeToMemory(&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: privDER,
})
return key.N.Bytes(), key.E, privPEM, err
}
+32
View File
@@ -0,0 +1,32 @@
package main
import (
"context"
"net/http"
"net/http/httptest"
"strconv"
"testing"
"github.com/julienschmidt/httprouter"
)
func TestReadIDParam(t *testing.T) {
app := newTestApplication(t)
const test_id int64 = 3
r := httptest.NewRequest(http.MethodGet, "/v1/issues/" + strconv.FormatInt(test_id, 10), nil)
params := httprouter.Params{{Key: "id", Value: "3"}}
ctx := context.WithValue(r.Context(), httprouter.ParamsKey, params)
r = r.WithContext(ctx)
id, err := app.readIDParam(r)
if err != nil {
t.Fatal(err)
}
if id != test_id {
t.Errorf("want %d, got id %d", test_id, id)
}
}
+86 -12
View File
@@ -12,35 +12,30 @@ import (
"errors"
"party.at/party/internal/data"
"party.at/party/internal/validator"
"encoding/hex"
)
func (app *application) listIssuesHandler(w http.ResponseWriter, r *http.Request) {
// To keep things consistent with our other handlers, we'll define an input struct
// to hold the expected values from the request query string.
var input struct {
Title string
data.Filters
}
// Initialize a new Validator instance.
v := validator.New()
// Call r.URL.Query() to get the url.Values map containing the query string data.
qs := r.URL.Query()
// Use our helpers to extract the title and genres query string values, falling back
// to defaults of an empty string and an empty slice respectively if they are not
// provided by the client.
input.Title = app.readString(qs, "title", "")
// input.Genres = app.readCSV(qs, "genres", []string{})
// Get the page and page_size query string values as integers. Notice that we set
// the default page value to 1 and default page_size to 20, and that we pass the
// validator instance as the final argument here.
input.Filters.Page = app.readInt(qs, "page", 1, v)
input.Filters.PageSize = app.readInt(qs, "page_size", 20, v)
// Extract the sort query string value, falling back to "id" if it is not provided
// by the client (which will imply a ascending sort on issue ID).
input.Filters.Sort = app.readString(qs, "sort", "id")
input.Filters.SortSafelist = []string{"id", "-id", "title", "-title", "description", "-description"}
@@ -77,11 +72,20 @@ func (app *application) createIssueHandler(w http.ResponseWriter, r *http.Reques
return
}
n, e, private_pem, err := GenerateIssueKey()
if err != nil {
app.serverErrorResponse(w, r, err)
return
}
issue := &data.Issue{
Title: input.Title,
Description: input.Description,
StartTime: input.StartTime,
EndTime: input.EndTime,
N: n,
E: e,
PrivatePem: private_pem,
}
v := validator.New()
@@ -219,3 +223,73 @@ func (app *application) deleteIssueHandler(w http.ResponseWriter, r *http.Reques
app.serverErrorResponse(w, r, err)
}
}
func (app *application) readIssuePubKeyHandler(w http.ResponseWriter, r *http.Request) {
id, err := app.readIDParam(r)
if err != nil {
app.notFoundResponse(w, r)
return
}
issue, err := app.models.Issues.Get(id)
if err != nil {
switch {
case errors.Is(err, data.ErrRecordNotFound):
app.notFoundResponse(w, r)
default:
app.serverErrorResponse(w, r, err)
}
return
}
type response struct {
N string `json:"n"`
E int `json:"e"`
}
res := response{
N: hex.EncodeToString(issue.N),
E: issue.E,
}
err = app.writeJSON(w, http.StatusOK, envelope{"public_key": res}, nil)
if err != nil {
app.serverErrorResponse(w, r, err)
}
}
func (app *application) blindSignIssueVoteHandler(w http.ResponseWriter, r *http.Request) {
id, err := app.readIDParam(r)
if err != nil {
app.notFoundResponse(w, r)
return
}
issue, err := app.models.Issues.Get(id)
if err != nil {
switch {
case errors.Is(err, data.ErrRecordNotFound):
app.notFoundResponse(w, r)
default:
app.serverErrorResponse(w, r, err)
}
return
}
type response struct {
N string `json:"n"`
E int `json:"e"`
}
res := response{
N: hex.EncodeToString(issue.N),
E: issue.E,
}
err = app.writeJSON(w, http.StatusOK, envelope{"public_key": res}, nil)
if err != nil {
app.serverErrorResponse(w, r, err)
}
}
+65
View File
@@ -0,0 +1,65 @@
package main
import (
"bytes"
"encoding/json"
"net/http"
"strconv"
"testing"
"time"
)
func TestReadIssueHandler(t *testing.T) {
app := newTestApplication(t)
ts := newTestServer(t, app, app.routes())
defer ts.Close()
token := ts.registerAndLogin(t, uniqueEmail(), "pa$$word123")
req := map[string]any{
"title": "An old silent pond...",
"description": "A frog jumps into the pond",
"start_time": time.Now().Format(time.RFC3339),
"end_time": time.Now().Add(24 * time.Hour).Format(time.RFC3339),
}
code, _, res := ts.postJSONWithToken(t, "/v1/issues", token, req)
if code != http.StatusCreated {
t.Fatalf("seed issue: want 201 got %d: %s", code, res)
}
var resp struct {
Issue struct {
ID int64 `json:"id"`
} `json:"issue"`
}
json.Unmarshal(res, &resp)
issueID := resp.Issue.ID
tests := []struct {
name string
urlPath string
wantCode int
wantBody []byte
}{
{"Valid ID", "/v1/issues/" + strconv.Itoa(int(issueID)), http.StatusOK, []byte("An old silent pond...")},
{"Non-existent ID", "/v1/issues/" + strconv.Itoa(int(issueID + 1)), http.StatusNotFound, nil},
{"Negative ID", "/v1/issues/-1", http.StatusNotFound, nil},
{"Decimal ID", "/v1/issues/1.23", http.StatusNotFound, nil},
{"String ID", "/v1/issues/foo", http.StatusNotFound, nil},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
code, _, body := ts.getWithToken(t, tt.urlPath, token)
if code != tt.wantCode {
t.Errorf("want %d; got %d", tt.wantCode, code)
}
if !bytes.Contains(body, tt.wantBody) {
t.Errorf("want body to contain %q; got %q", tt.wantBody, string(body))
}
})
}
}
+66 -4
View File
@@ -24,6 +24,10 @@ import (
"party.at/party/internal/data"
"party.at/party/internal/mailer"
"party.at/party/internal/jsonlog"
"crypto/rand"
"crypto/aes"
"crypto/cipher"
)
var version string
@@ -80,12 +84,31 @@ var upgrader = websocket.Upgrader{
func main() {
fmt.Printf("Full Args: %v\n", os.Args)
// 32 bytes = AES-256
var key [32]byte
if _, err := rand.Read(key[:]); err != nil {
panic(err)
}
message := []byte("hello secure world")
nonce, ciphertext, err := encrypt(key, message)
if err != nil {
panic(err)
}
plaintext, err := decrypt(key, nonce, ciphertext)
if err != nil {
panic(err)
}
fmt.Printf("Original: %s\n", message)
fmt.Printf("Decrypted: %s\n", plaintext)
var cfg config
flag.IntVar(&cfg.port, "port", 4000, "API server port")
flag.StringVar(&cfg.env, "env", "development", "Environment (development|staging|production)")
flag.StringVar(&cfg.env, "env", "production", "Environment (development|staging|production)")
flag.StringVar(&cfg.db.dsn, "db-dsn", os.Getenv("PARTY_DB_DSN"), "PostgreSQL DSN")
//addr := flag.String("addr", ":8443", "HTTP network address")
@@ -97,7 +120,7 @@ func main() {
flag.IntVar(&cfg.smtp.port, "smtp-port", 25, "SMTP port")
flag.StringVar(&cfg.smtp.username, "smtp-username", "98cf60028d7fcb", "SMTP username")
flag.StringVar(&cfg.smtp.password, "smtp-password", "b9d4a35372e971", "SMTP password")
flag.StringVar(&cfg.smtp.sender, "smtp-sender", "Greenlight <no-reply@greenlight.alexedwards.net>", "SMTP sender")
flag.StringVar(&cfg.smtp.sender, "smtp-sender", "DPÖ <no-reply@party.at>", "SMTP sender")
flag.Float64Var(&cfg.limiter.rps, "limiter-rps", 2, "Rate limiter maximum requests per second")
flag.IntVar(&cfg.limiter.burst, "limiter-burst", 4, "Rate limiter maximum burst")
@@ -126,7 +149,6 @@ func main() {
if err != nil {
logger.PrintFatal(err, nil)
}
defer db.Close()
expvar.NewString("version").Set(version)
@@ -188,3 +210,43 @@ func openDB(cfg config) (*sql.DB, error) {
return db, nil
}
func encrypt(key [32]byte, plaintext []byte) (nonce, ciphertext []byte, err error) {
block, err := aes.NewCipher(key[:])
if err != nil {
return nil, nil, err
}
aead, err := cipher.NewGCM(block)
if err != nil {
return nil, nil, err
}
nonce = make([]byte, aead.NonceSize())
if _, err := rand.Read(nonce); err != nil {
panic(err)
}
ciphertext = aead.Seal(nil, nonce, plaintext, nil)
return nonce, ciphertext, nil
}
func decrypt(key [32]byte, nonce, ciphertext []byte) ([]byte, error) {
block, err := aes.NewCipher(key[:])
if err != nil {
return nil, err
}
aead, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
plaintext, err := aead.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, err
}
return plaintext, nil
}
+1 -1
View File
@@ -64,7 +64,7 @@ func (app *application) rateLimit(next http.Handler) http.Handler {
// Loop through all clients. If they haven't been seen within the last three
// minutes, delete the corresponding entry from the map.
for ip, client := range clients {
if time.Since(client.lastSeen) > 3*time.Minute {
if time.Since(client.lastSeen) > 3 * time.Minute {
delete(clients, ip)
}
}
+8 -5
View File
@@ -27,15 +27,18 @@ func (app *application) routes() http.Handler {
router.HandlerFunc(http.MethodPatch, "/v1/issues/:id", app.requirePermission("issues:write", app.updateIssueHandler))
router.HandlerFunc(http.MethodDelete, "/v1/issues/:id", app.requirePermission("issues:write", app.deleteIssueHandler))
router.HandlerFunc(http.MethodPost, "/v1/users", app.createUserHandler)
router.HandlerFunc(http.MethodGet, "/v1/issues/:id/pubkey", app.requirePermission("issues:read", app.readIssuePubKeyHandler))
router.HandlerFunc(http.MethodPost, "/v1/issues/:id/blind-sign", app.requirePermission("issues:read", app.blindSignIssueVoteHandler))
router.HandlerFunc(http.MethodPost, "/v1/users", app.createUserHandler)
// router.HandlerFunc(http.MethodGet, "/v1/users/:id", app.readUserHandler)
// router.HandlerFunc(http.MethodPatch, "/v1/users/:id", app.updateUserHandler)
router.HandlerFunc(http.MethodDelete, "/v1/users/:id", app.deleteUserHandler)
router.HandlerFunc(http.MethodPut, "/v1/users/activated", app.activateUserHandler)
router.HandlerFunc(http.MethodDelete, "/v1/users/:id", app.deleteUserHandler)
router.HandlerFunc(http.MethodPut, "/v1/users/activated", app.activateUserHandler)
router.HandlerFunc(http.MethodPost, "/v1/tokens/authentication", app.createAuthenticationTokenHandler)
router.HandlerFunc(http.MethodPost, "/v1/tokens/authentication", app.createAuthenticationTokenHandler)
router.Handler(http.MethodGet, "/debug/vars", expvar.Handler())
router.Handler (http.MethodGet, "/debug/vars", expvar.Handler())
return app.metrics(app.recoverPanic(app.enableCORS(app.rateLimit(app.authenticate(router)))))
}
+202
View File
@@ -0,0 +1,202 @@
package main
import (
"io"
"net/http"
"net/http/httptest"
"testing"
"os"
"encoding/json"
"bytes"
"fmt"
"time"
"party.at/party/internal/data"
"party.at/party/internal/jsonlog"
)
func newTestApplication(t *testing.T) *application {
cfg := config{}
cfg.db.dsn = "postgres://party:password@localhost:5432/party?sslmode=disable"
cfg.db.maxOpenConns = 25
cfg.db.maxIdleConns = 25
cfg.db.maxIdleTime = "15m"
cfg.limiter.enabled = false
cfg.env = "development"
logger := jsonlog.New(os.Stdout, jsonlog.LevelInfo)
db, err := openDB(cfg)
if err != nil {
logger.PrintFatal(err, nil)
}
t.Cleanup(func() {db.Close()})
return &application{
logger: logger,
models: data.NewModels(db),
config: cfg,
}
}
type testServer struct {
*httptest.Server
app *application
}
func newTestServer(t *testing.T, app *application, h http.Handler) *testServer {
ts := httptest.NewTLSServer(h)
return &testServer{ts, app}
}
func (ts *testServer) postJSON(t *testing.T, path string, body any) (int, http.Header, []byte) {
t.Helper()
b, err := json.Marshal(body)
if err != nil {
t.Fatal(err)
}
req, err := http.NewRequest(http.MethodPost, ts.URL+path, bytes.NewReader(b))
if err != nil {
t.Fatal(err)
}
req.Header.Set("Content-Type", "application/json")
resp, err := ts.Client().Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
return resp.StatusCode, resp.Header, respBody
}
func (ts *testServer) get(t *testing.T, path string) (int, http.Header, []byte) {
t.Helper()
rs, err := ts.Client().Get(ts.URL + path)
if err != nil {
t.Fatal(err)
}
defer rs.Body.Close()
body, err := io.ReadAll(rs.Body)
if err != nil {
t.Fatal(err)
}
return rs.StatusCode, rs.Header, body
}
// registers a user, activates them, logs in, returns the bearer token
func (ts *testServer) registerAndLogin(t *testing.T, email, password string) string {
t.Helper()
// 1. Register
registerBody := map[string]any{
"email": email,
"password": password,
"username": email,
"name": "Test User",
"alt_name" : "",
"provider_id": 1,
}
code, _, body := ts.postJSON(t, "/v1/users", registerBody)
if code != http.StatusCreated {
t.Fatalf("register: want 201 got %d: %s", code, body)
}
// 2. Activate — if your flow requires it, either hit the endpoint
// or directly flip the activated flag in the test DB
// ts.activateUser(t, email)
// 3. Login
loginBody := map[string]string{"email": email, "password": password}
code, _, body = ts.postJSON(t, "/v1/tokens/authentication", loginBody)
if code != http.StatusCreated {
t.Fatalf("login: want 201 got %d: %s", code, body)
}
// 4. Parse token out of response
var resp struct {
AuthenticationToken struct {
Token string `json:"token"`
} `json:"authentication_token"`
}
if err := json.Unmarshal(body, &resp); err != nil {
t.Fatalf("parse token: %v", err)
}
return resp.AuthenticationToken.Token
}
// activateUser directly updates the DB — avoids needing a real email flow
// func (ts *testServer) activateUser(t *testing.T, email string) {
// t.Helper()
// _, err := ts.app.db.Exec("UPDATE users SET activated = true WHERE email = $1", email)
// if err != nil {
// t.Fatalf("activate user: %v", err)
// }
// }
// like ts.get but adds Authorization header
func (ts *testServer) getWithToken(t *testing.T, path, token string) (int, http.Header, []byte) {
t.Helper()
req, err := http.NewRequest(http.MethodGet, ts.URL+path, nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+token)
rs, err := ts.Client().Do(req)
if err != nil {
t.Fatal(err)
}
defer rs.Body.Close()
body, err := io.ReadAll(rs.Body)
if err != nil {
t.Fatal(err)
}
return rs.StatusCode, rs.Header, body
}
func (ts *testServer) postJSONWithToken(t *testing.T, path, token string, body any) (int, http.Header, []byte) {
t.Helper()
b, err := json.Marshal(body)
if err != nil {
t.Fatal(err)
}
req, err := http.NewRequest(http.MethodPost, ts.URL+path, bytes.NewReader(b))
if err != nil {
t.Fatal(err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)
rs, err := ts.Client().Do(req)
if err != nil {
t.Fatal(err)
}
defer rs.Body.Close()
respBody, err := io.ReadAll(rs.Body)
if err != nil {
t.Fatal(err)
}
return rs.StatusCode, rs.Header, respBody
}
func uniqueEmail() string {
return fmt.Sprintf("test_%d@example.com", time.Now().UnixNano())
}
+44 -25
View File
@@ -5,23 +5,22 @@ import (
"net/http"
"party.at/party/internal/data"
"party.at/party/internal/validator"
"database/sql"
"time"
)
func (app *application) createUserHandler(w http.ResponseWriter, r *http.Request) {
var input struct {
ProviderId int64 `json:"provider_id"`
Username string `json:"username"`
PhoneNumber string `json:"phone_number"`
Country string `json:"country"`
Email string `json:"email"`
Password string `json:"password"`
Name string `json:"name"`
AltName string `json:"alt_name"`
ProviderId int64 `json:"provider_id"`
Username string `json:"username"`
PhoneNumber string `json:"phone_number"`
Country string `json:"country"`
Email string `json:"email"`
Password string `json:"password"`
Name string `json:"name"`
AltName *string `json:"alt_name"`
DateOfBirth time.Time `json:"date_of_birth"`
Address string `json:"address"`
Address string `json:"address"`
}
err := app.readJSON(w, r, &input)
@@ -35,12 +34,16 @@ func (app *application) createUserHandler(w http.ResponseWriter, r *http.Request
PhoneNumber: input.PhoneNumber,
Country: input.Country,
Name: input.Name,
AltName: sql.NullString{String: input.AltName, Valid: true},
AltName: input.AltName,
DateOfBirth: input.DateOfBirth,
Address: input.Address,
Activated: false,
}
if app.config.env == "development" {
user.Activated = true
}
userIdentity := &data.UserIdentity{
ProviderID: input.ProviderId,
ProviderUserID: input.Username,
@@ -85,27 +88,43 @@ func (app *application) createUserHandler(w http.ResponseWriter, r *http.Request
return
}
token, err := app.models.Tokens.New(user.ID, userIdentity.ID, 3 * 24 * time.Hour, data.ScopeActivation)
if app.config.env == "development" {
err = app.models.Permissions.AddForUser(user.ID, "issues:write")
if err != nil {
app.serverErrorResponse(w, r, err)
return
}
}
if app.config.env == "production" {
token, err := app.models.Tokens.New(user.ID, userIdentity.ID, 3 * 24 * time.Hour, data.ScopeActivation)
if err != nil {
app.serverErrorResponse(w, r, err)
return
}
app.background(func() {
data := map[string]interface{}{
"token": token.Plaintext,
"userID": user.ID,
}
err = app.mailer.Send(user.Email, "user_welcome.tmpl", data)
if err != nil {
app.logger.PrintError(err, nil)
}
})
}
authentication_token, err := app.models.Tokens.New(user.ID, userIdentity.ID, 24 * time.Hour, data.ScopeAuthentication)
if err != nil {
app.serverErrorResponse(w, r, err)
return
}
app.background(func() {
data := map[string]interface{}{
"token": token.Plaintext,
"userID": user.ID,
}
err = app.mailer.Send(user.Email, "user_welcome.tmpl", data)
if err != nil {
app.logger.PrintError(err, nil)
}
})
// Write a JSON response containing the user data along with a 201 Created status
// code.
err = app.writeJSON(w, http.StatusCreated, envelope{"user": user}, nil)
err = app.writeJSON(w, http.StatusCreated, envelope{"user": user, "authentication_token": authentication_token}, nil)
if err != nil {
app.serverErrorResponse(w, r, err)
}