Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ services:
- pg_password
- pg_dbname
entrypoint: /run-migration.sh
command: ""
command: ["up"]
depends_on:
api-db:
condition: service_healthy
Expand Down
29 changes: 29 additions & 0 deletions pkg/auth/schema_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package auth

import (
"reflect"
"testing"
)

func TestSchemaConstants(t *testing.T) {
tests := []struct {
name string
got any
want any
}{
{"PublicKeyPrefix", PublicKeyPrefix, "pk_"},
{"SecretKeyPrefix", SecretKeyPrefix, "sk_"},
{"TokenMinLength", TokenMinLength, 16},
{"AccountNameMinLength", AccountNameMinLength, 5},
{"EncryptionKeyLength", EncryptionKeyLength, 32},
}

for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
if !reflect.DeepEqual(tt.got, tt.want) {
t.Errorf("%s = %v, want %v", tt.name, tt.got, tt.want)
}
})
}
}
33 changes: 33 additions & 0 deletions pkg/cli/colour_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package cli

import (
"reflect"
"testing"
)

func TestColourConstants(t *testing.T) {
tests := []struct {
name string
got any
want any
}{
{"Reset", Reset, "\033[0m"},
{"RedColour", RedColour, "\033[31m"},
{"GreenColour", GreenColour, "\033[32m"},
{"YellowColour", YellowColour, "\033[33m"},
{"BlueColour", BlueColour, "\033[34m"},
{"MagentaColour", MagentaColour, "\033[35m"},
{"CyanColour", CyanColour, "\033[36m"},
{"GrayColour", GrayColour, "\033[37m"},
{"WhiteColour", WhiteColour, "\033[97m"},
}

for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
if !reflect.DeepEqual(tt.got, tt.want) {
t.Errorf("%s = %q, want %q", tt.name, tt.got, tt.want)
}
})
}
}
5 changes: 3 additions & 2 deletions pkg/middleware/token_middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -256,8 +256,9 @@ func (t TokenCheckMiddleware) shallReject(logger *slog.Logger, accountName, publ
return t.getUnauthenticatedError()
}

// Compute local signature over canonical request and compare in constant time (hash to fixed-length first)
localSignature := auth.CreateSignatureFrom(canonical, token.PublicKey) //@todo Change!
// Compute local signature over canonical request using the account's secret key
// and compare in constant time (hash to fixed-length first)
localSignature := auth.CreateSignatureFrom(canonical, token.SecretKey)
Comment on lines +259 to +261

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The indentation for these new lines appears to be using spaces instead of tabs. The standard Go format (gofmt) uses tabs for indentation. Please run gofmt on the file to fix the formatting for consistency.

Suggested change
// Compute local signature over canonical request using the account's secret key
// and compare in constant time (hash to fixed-length first)
localSignature := auth.CreateSignatureFrom(canonical, token.SecretKey)
// Compute local signature over canonical request using the account's secret key
// and compare in constant time (hash to fixed-length first)
localSignature := auth.CreateSignatureFrom(canonical, token.SecretKey)

hSig := sha256.Sum256([]byte(strings.TrimSpace(signature)))
hLocal := sha256.Sum256([]byte(localSignature))

Expand Down
26 changes: 13 additions & 13 deletions pkg/middleware/token_middleware_additional_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ func TestTokenMiddleware_PublicTokenMismatch(t *testing.T) {
next := func(w http.ResponseWriter, r *http.Request) *pkgHttp.ApiError { return nil }
handler := tm.Handle(next)

req := makeSignedRequest(t, http.MethodGet, "https://api.test.local/v1/x", "", seed.AccountName, "wrong-"+seed.PublicKey, seed.SecretKey, time.Now(), "nonce-mm", "req-mm")
req := makeSignedRequest(t, http.MethodGet, "https://api.test.local/v1/x", "", seed.AccountName, "wrong-"+seed.PublicKey, seed.SecretKey, time.Now(), "nonce-mm", "req-mm")

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This line is indented with spaces instead of tabs. Please run gofmt on this file to ensure consistent formatting with the rest of the codebase. This issue is present on other new lines in this file as well.

Suggested change
req := makeSignedRequest(t, http.MethodGet, "https://api.test.local/v1/x", "", seed.AccountName, "wrong-"+seed.PublicKey, seed.SecretKey, time.Now(), "nonce-mm", "req-mm")
req := makeSignedRequest(t, http.MethodGet, "https://api.test.local/v1/x", "", seed.AccountName, "wrong-"+seed.PublicKey, seed.SecretKey, time.Now(), "nonce-mm", "req-mm")

req.Header.Set("X-Forwarded-For", "1.1.1.1")
rec := httptest.NewRecorder()
if err := handler(rec, req); err == nil || err.Status != http.StatusUnauthorized {
Expand All @@ -112,7 +112,7 @@ func TestTokenMiddleware_SignatureMismatch(t *testing.T) {
next := func(w http.ResponseWriter, r *http.Request) *pkgHttp.ApiError { return nil }
handler := tm.Handle(next)

req := makeSignedRequest(t, http.MethodPost, "https://api.test.local/v1/x", "body", seed.AccountName, seed.PublicKey, seed.SecretKey, time.Now(), "nonce-sig", "req-sig")
req := makeSignedRequest(t, http.MethodPost, "https://api.test.local/v1/x", "body", seed.AccountName, seed.PublicKey, seed.SecretKey, time.Now(), "nonce-sig", "req-sig")
req.Header.Set("X-Forwarded-For", "1.1.1.1")
req.Header.Set("X-API-Signature", req.Header.Get("X-API-Signature")+"tamper")
rec := httptest.NewRecorder()
Expand All @@ -133,7 +133,7 @@ func TestTokenMiddleware_NonceReplay(t *testing.T) {
}
handler := tm.Handle(next)

req := makeSignedRequest(t, http.MethodPost, "https://api.test.local/v1/x", "{}", seed.AccountName, seed.PublicKey, seed.SecretKey, time.Now(), "nonce-rp", "req-rp")
req := makeSignedRequest(t, http.MethodPost, "https://api.test.local/v1/x", "{}", seed.AccountName, seed.PublicKey, seed.SecretKey, time.Now(), "nonce-rp", "req-rp")
req.Header.Set("X-Forwarded-For", "1.1.1.1")
rec := httptest.NewRecorder()
if err := handler(rec, req); err != nil {
Expand Down Expand Up @@ -161,22 +161,22 @@ func TestTokenMiddleware_RateLimiter(t *testing.T) {

// Pre-warm limiter by sending invalid signature requests up to the limit
for i := 0; i < tm.maxFailPerScope; i++ {
req := makeSignedRequest(
t, http.MethodGet, "https://api.test.local/v1/rl", "",
seed.AccountName, seed.PublicKey, "wrong-secret", time.Now(),
fmt.Sprintf("nonce-rl-%d", i), fmt.Sprintf("req-rl-%d", i),
)
req := makeSignedRequest(
t, http.MethodGet, "https://api.test.local/v1/rl", "",
seed.AccountName, seed.PublicKey, "wrong-secret", time.Now(),
fmt.Sprintf("nonce-rl-%d", i), fmt.Sprintf("req-rl-%d", i),
)
req.Header.Set("X-Forwarded-For", "9.9.9.9")
rec := httptest.NewRecorder()
_ = handler(rec, req) // ignore errors while warming
}

// Next request with valid signature should be rate limited
req := makeSignedRequest(
t, http.MethodGet, "https://api.test.local/v1/rl", "",
seed.AccountName, seed.PublicKey, seed.SecretKey, time.Now(),
"nonce-rl-final", "req-rl-final",
)
req := makeSignedRequest(
t, http.MethodGet, "https://api.test.local/v1/rl", "",
seed.AccountName, seed.PublicKey, seed.SecretKey, time.Now(),
"nonce-rl-final", "req-rl-final",
)
req.Header.Set("X-Forwarded-For", "9.9.9.9")
rec := httptest.NewRecorder()
err := handler(rec, req)
Expand Down
55 changes: 28 additions & 27 deletions pkg/middleware/token_middleware_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,8 @@ func generate32(t *testing.T) []byte {
return buf
}

// makeSignedRequest builds a request with required headers and a valid HMAC signature over the canonical string.
// makeSignedRequest builds a request with required headers and a valid HMAC
// signature over the canonical string using the account's secret key.
func makeSignedRequest(t *testing.T, method, rawURL, body, account, public, secret string, ts time.Time, nonce, reqID string) *http.Request {
t.Helper()
var bodyBuf *bytes.Buffer
Expand All @@ -226,8 +227,8 @@ func makeSignedRequest(t *testing.T, method, rawURL, body, account, public, secr
req.Header.Set("X-API-Nonce", nonce)

bodyHash := portal.Sha256Hex([]byte(body))
canonical := portal.BuildCanonical(method, req.URL, account, public, req.Header.Get("X-API-Timestamp"), nonce, bodyHash)
sig := auth.CreateSignatureFrom(canonical, secret)
canonical := portal.BuildCanonical(method, req.URL, account, public, req.Header.Get("X-API-Timestamp"), nonce, bodyHash)
sig := auth.CreateSignatureFrom(canonical, secret)
Comment on lines +230 to +231

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

These lines are indented with spaces instead of tabs. Please run gofmt on this file to ensure consistent formatting. This issue appears on other new lines in this file as well.

Suggested change
canonical := portal.BuildCanonical(method, req.URL, account, public, req.Header.Get("X-API-Timestamp"), nonce, bodyHash)
sig := auth.CreateSignatureFrom(canonical, secret)
canonical := portal.BuildCanonical(method, req.URL, account, public, req.Header.Get("X-API-Timestamp"), nonce, bodyHash)
sig := auth.CreateSignatureFrom(canonical, secret)

req.Header.Set("X-API-Signature", sig)
return req
}
Expand Down Expand Up @@ -273,12 +274,12 @@ func TestTokenMiddleware_DB_Integration(t *testing.T) {
http.MethodPost,
"https://api.test.local/v1/posts?z=9&a=1",
"{\"title\":\"ok\"}",
seed.AccountName,
seed.PublicKey,
seed.SecretKey,
now,
"nonce-1",
"req-001",
seed.AccountName,
seed.PublicKey,
seed.SecretKey,
now,
"nonce-1",
"req-001",
)
rec := httptest.NewRecorder()
if err := handler(rec, req); err != nil {
Expand All @@ -294,12 +295,12 @@ func TestTokenMiddleware_DB_Integration(t *testing.T) {
http.MethodGet,
"https://api.test.local/v1/ping",
"",
"no-such-user",
seed.PublicKey,
seed.SecretKey,
now,
"nonce-2",
"req-002",
"no-such-user",
seed.PublicKey,
seed.SecretKey,
now,
"nonce-2",
"req-002",
)
rec = httptest.NewRecorder()
if err := handler(rec, reqUnknown); err == nil || err.Status != http.StatusUnauthorized {
Expand Down Expand Up @@ -350,12 +351,12 @@ func TestTokenMiddleware_DB_Integration_HappyPath(t *testing.T) {
http.MethodPost,
"https://api.test.local/v1/resource?b=2&a=1",
"{\"x\":123}",
seed.AccountName,
seed.PublicKey,
seed.SecretKey,
time.Now(),
"n-happy-1",
"rid-happy-1",
seed.AccountName,
seed.PublicKey,
seed.SecretKey,
time.Now(),
"n-happy-1",
"rid-happy-1",
)
rec := httptest.NewRecorder()
if err := handler(rec, req); err != nil {
Expand Down Expand Up @@ -416,12 +417,12 @@ func TestTokenMiddleware_RejectsFutureTimestamps(t *testing.T) {
http.MethodGet,
"https://api.test.local/v1/test",
"",
seed.AccountName,
seed.PublicKey,
seed.SecretKey,
futureTime,
"n-future-1",
"rid-future-1",
seed.AccountName,
seed.PublicKey,
seed.SecretKey,
futureTime,
"n-future-1",
"rid-future-1",
)
rec := httptest.NewRecorder()

Expand Down
Loading