feat: complete API-driven projects with infrastructure and business acceptance

This commit is contained in:
2026-09-23 17:33:50 +08:00
parent 04a1f7999d
commit 2c74dc0859
137 changed files with 11926 additions and 105 deletions

View File

@@ -0,0 +1,40 @@
package middleware
import (
"crypto/sha256"
"crypto/subtle"
"errors"
apierrors "git.yuntuo.hk/k2safe/go-omni/errors"
"git.yuntuo.hk/k2safe/go-omni/httpx"
"os"
"strings"
)
// Auth is the fail-closed registry default. Startup replaces it with configured
// authentication. This administrative example uses one environment-only key;
// production applications can inject JWT/OIDC through the same middleware slot.
func Auth(next httpx.Handler) httpx.Handler {
return func(c *httpx.Context) error {
return apierrors.Unauthorized("UNAUTHENTICATED", "authentication required")
}
}
func NewAuthFromEnv() (httpx.Middleware, error) {
token := os.Getenv("USER_SERVICE_API_TOKEN")
if len(token) < 32 || strings.ContainsAny(token, " \t\r\n") {
return nil, errors.New("USER_SERVICE_API_TOKEN requires at least 32 bytes without whitespace")
}
expected := sha256.Sum256([]byte(token))
return func(next httpx.Handler) httpx.Handler {
return func(c *httpx.Context) error {
parts := strings.Fields(c.Header("Authorization"))
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
return apierrors.Unauthorized("UNAUTHENTICATED", "authentication required")
}
actual := sha256.Sum256([]byte(parts[1]))
if subtle.ConstantTimeCompare(expected[:], actual[:]) != 1 {
return apierrors.Unauthorized("UNAUTHENTICATED", "authentication required")
}
return next(c)
}
}, nil
}

View File

@@ -0,0 +1,35 @@
package middleware
import (
apierrors "git.yuntuo.hk/k2safe/go-omni/errors"
"git.yuntuo.hk/k2safe/go-omni/httpx"
"net/http/httptest"
"testing"
)
func TestAuthFailsClosedAndDoesNotLeakKey(t *testing.T) {
t.Setenv("USER_SERVICE_API_TOKEN", "")
if _, err := NewAuthFromEnv(); err == nil {
t.Fatal("missing credential accepted")
}
token := "test-key-012345678901234567890123456789"
t.Setenv("USER_SERVICE_API_TOKEN", token)
middleware, err := NewAuthFromEnv()
if err != nil {
t.Fatal(err)
}
for _, header := range []string{"", "Basic " + token, "Bearer wrong", "Bearer " + token} {
called := false
r := httptest.NewRequest("GET", "/", nil)
r.Header.Set("Authorization", header)
c := httpx.NewContext(r, httptest.NewRecorder(), nil)
err = middleware(func(*httpx.Context) error { called = true; return nil })(c)
if header == "Bearer "+token {
if err != nil || !called {
t.Fatal("valid token rejected")
}
} else if err == nil || called || apierrors.From(err).Status != 401 {
t.Fatal("unauthenticated request reached service")
}
}
}

View File

@@ -0,0 +1,10 @@
// Code generated by go-omni api. DO NOT EDIT.
package middleware
import "git.yuntuo.hk/k2safe/go-omni/httpx"
func Defaults() map[string]httpx.Middleware {
return map[string]httpx.Middleware{
"Auth": Auth,
}
}