generated from coulomb/repo-seed
feat(WP-0010): IHF Phase 9 — External API Surface and Consumer SDKs
Some checks failed
Test / test (push) Has been cancelled
Some checks failed
Test / test (push) Has been cancelled
Delivers the full Phase 9 external API layer: - Versioned REST API (/api/v2/) with OpenAPI 3.1 spec; enum arrays for widget_type, event_type, annotation category drawn live from registry tables - OAuth 2.0 client credentials flow (/api/v2/token); hub:*:write scopes gated on active HubCapabilityManifest FK - API key management: SHA256-hashed tokens, key_prefix for display, one-time reveal on creation, revocation support - TypeScript and Python consumer SDKs generated from registry tables (/api/v2/sdk/ihf-client.ts, /api/v2/sdk/ihf-client.py) - Webhook delivery: HMAC-SHA256 signing, append-only webhook_deliveries, fire-and-forget dispatch via forkIO, 3-retry logic - Admin API dashboard with 24h stats (request count, error rate, last seen) - Rate limiting (per-minute) and daily quota enforcement via api_request_log - Schema migration: api_consumers, api_keys, webhook_subscriptions (CHECK constraint on 6 framework lifecycle topics), webhook_deliveries (append-only trigger), api_request_log - ARCHITECTURE-LAYERS.md scorecard: 3.34 → 3.41 (approaching Strong) - contracts/functional/interaction-reporting-v1.md extended with Phase 9 endpoint catalogue and 422 validation error format GAAF: no bare TEXT discriminators; webhook event_type uses CHECK constraint over 6 allowed framework lifecycle topic strings (not widget event types). Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
87
Web/Controller/Api/V2/Auth.hs
Normal file
87
Web/Controller/Api/V2/Auth.hs
Normal file
@@ -0,0 +1,87 @@
|
||||
module Web.Controller.Api.V2.Auth where
|
||||
|
||||
import IHP.Prelude
|
||||
import IHP.ControllerPrelude
|
||||
import Web.Types
|
||||
import Generated.Types
|
||||
import Data.Aeson (object, (.=))
|
||||
import qualified Data.Text as T
|
||||
import qualified Data.Text.Encoding as TE
|
||||
import qualified Crypto.Hash.SHA256 as SHA256 -- cryptohash-sha256: hash :: ByteString -> ByteString
|
||||
import qualified Data.ByteString.Base16 as Base16
|
||||
import Network.Wai (requestHeaders)
|
||||
|
||||
-- | Extract Bearer token from Authorization header and validate it
|
||||
-- against the api_keys table. Returns the ApiConsumer on success,
|
||||
-- or halts with 401 JSON on failure.
|
||||
requireApiConsumer :: (?context :: ControllerContext, ?modelContext :: ModelContext, ?respond :: Respond, ?request :: Request) => IO ApiConsumer
|
||||
requireApiConsumer = do
|
||||
let authHeader = lookup "Authorization" (requestHeaders ?request)
|
||||
let mToken = authHeader >>= \h ->
|
||||
let t = cs h :: Text
|
||||
in if "Bearer " `T.isPrefixOf` t
|
||||
then Just (T.drop 7 t)
|
||||
else Nothing
|
||||
case mToken of
|
||||
Nothing -> unauthorized401
|
||||
Just token -> do
|
||||
let tokenHash = hashApiKey token
|
||||
now <- getCurrentTime
|
||||
mKey <- query @ApiKey
|
||||
|> filterWhere (#keyHash, tokenHash)
|
||||
|> fetchOneOrNothing
|
||||
case mKey of
|
||||
Nothing -> unauthorized401
|
||||
Just apiKey -> do
|
||||
when (isJust apiKey.revokedAt) unauthorized401
|
||||
when (maybe False (< now) apiKey.expiresAt) do
|
||||
respondWithStatus 401 $ object
|
||||
[ "error" .= ("Token expired" :: Text)
|
||||
, "code" .= ("token_expired" :: Text)
|
||||
]
|
||||
-- Update last_used_at (fire-and-forget; do not block on failure)
|
||||
apiKey |> set #lastUsedAt (Just now) |> updateRecord
|
||||
fetch apiKey.apiConsumerId >>= \consumer -> do
|
||||
unless consumer.isActive unauthorized401
|
||||
pure consumer
|
||||
|
||||
unauthorized401 :: (?respond :: Respond) => IO a
|
||||
unauthorized401 = respondWithStatus 401 $ object
|
||||
[ "error" .= ("Unauthorized" :: Text)
|
||||
, "code" .= ("invalid_api_key" :: Text)
|
||||
]
|
||||
|
||||
respondWithStatus :: (?respond :: Respond) => Int -> Value -> IO a
|
||||
respondWithStatus status body = do
|
||||
respondAndExit $ responseLBS
|
||||
(toEnum status)
|
||||
[("Content-Type", "application/json")]
|
||||
(encode body)
|
||||
|
||||
-- | SHA-256 hex hash of the key (same as stored in key_hash column)
|
||||
hashApiKey :: Text -> Text
|
||||
hashApiKey key =
|
||||
let bytes = TE.encodeUtf8 key
|
||||
digest = SHA256.hash bytes
|
||||
in TE.decodeUtf8 (Base16.encode digest)
|
||||
|
||||
-- | Standard paginated response envelope
|
||||
paginatedResponse :: ToJSON a => [a] -> Int -> Int -> Int -> Value
|
||||
paginatedResponse items page perPage total =
|
||||
object
|
||||
[ "data" .= items
|
||||
, "meta" .= object
|
||||
[ "page" .= page
|
||||
, "per_page" .= perPage
|
||||
, "total" .= total
|
||||
]
|
||||
]
|
||||
|
||||
-- | Parse page / per_page query params with sensible defaults
|
||||
getPageParams :: (?context :: ControllerContext) => IO (Int, Int)
|
||||
getPageParams = do
|
||||
page <- fromMaybe 1 <$> paramOrNothing @Int "page"
|
||||
perPage <- fromMaybe 50 <$> paramOrNothing @Int "per_page"
|
||||
let perPage' = min 200 (max 1 perPage)
|
||||
let page' = max 1 page
|
||||
pure (page', perPage')
|
||||
Reference in New Issue
Block a user