belt 0.6.11 → 0.6.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: dd41febdeffceff192d2ce0c71193a0d44f6bc9bf573361e2473aed29f75c845
4
- data.tar.gz: 48c1cce20c99bdf8e1aac26af043a6b2fc16438007d6840e18fa8a8d17607b6e
3
+ metadata.gz: 6ade807d379d6c17989f8b4e15363f5616b1429e72c709f43bd98b99206ca929
4
+ data.tar.gz: c075c8e052e661a06637b0974266f4d69653a1abb410084ea4aff99553f77752
5
5
  SHA512:
6
- metadata.gz: 7d44de9ce0d9f79fa3247cb32d7eab77859bc5da28167b1d3a9efd34e391c024f130d5d7486a5b053b9a0d4d425a6183657e2b1009ab13a48f9c1dc0284edeed
7
- data.tar.gz: f757091a23142d205428a6161afe26033520229623950f8455b336ffd99135d29efc64fd40b1ef76f67035644780c21fe9ce844e56b3a6c69a56893da10bff81
6
+ metadata.gz: bc607607b2fc6e52523614928c139e6e946d5a2f0b3ddb0b6913bef53043cedc16d8cf017a2976e1e1d42080e9972ff65fea369a99b276311ef11bd7d41ab0a3
7
+ data.tar.gz: cf014b618dcbd8311eddbb55291d07049d24ad00931ce47567d004e716eff75c6caab9f4a128b6697c6d5cd0db0e25a8d96c920e0862f8f042e0628279c438d3
data/CHANGELOG.md CHANGED
@@ -1,5 +1,78 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.13
4
+
5
+ ### Added
6
+
7
+ - **A model can choose a GSI's projection.** An `indexes(...)` entry takes
8
+ `projection: :keys_only` or `projection: { include: %w[warnTurn] }`, and
9
+ `belt setup tables` writes `projection_type = "KEYS_ONLY"` / `"INCLUDE"` (with
10
+ `non_key_attributes`) instead of always `"ALL"`. `belt generate index` takes
11
+ `--projection keys_only|all|include:a,b`. `ALL` stays the default, so existing
12
+ apps regenerate the same file. A narrower index stops every write to a row from
13
+ rewriting its full copy in the index; queries on it return only the projected
14
+ attributes, so read the rest with `find`. A projection the generator can't read
15
+ aborts instead of falling back to `ALL`, and a regen that would turn a
16
+ hand-set `KEYS_ONLY`/`INCLUDE` back into `ALL` is treated like a dropped GSI
17
+ (prompt, or skip on generator sync). See `belt explain models`.
18
+
19
+ ### Added
20
+
21
+ - **`throttle:` cascades in routes.rb.** `gateway :api, throttle: { rate:, burst: }`
22
+ sets a default for every route; `scope`, `namespace`, `function` and
23
+ `resources` blocks pass theirs down to the routes inside (nested resources,
24
+ `member` / `collection` included). The nearest one wins, and `throttle: false`
25
+ on a route or block opts out. A bad value now fails on the line that declares
26
+ it. A gateway default is a route-level throttle, so it wins over
27
+ `config/lambda/<fn>.yml` `throttle:` and the provider's stage `throttle`.
28
+ (Fizzy #2010)
29
+ - `belt explain routing` has a Throttling section. It explains that API Gateway
30
+ limits are per route, not per caller, and includes a WAF rate-based-rule recipe
31
+ (REGIONAL web ACL, scoped down to the routes that cost money, attached through
32
+ conveyor-belt's `waf_web_acl_arn`) for per-IP limits. `belt explain throttle`,
33
+ `rate_limit` and `waf` open it.
34
+
35
+ ### Security
36
+
37
+ - **A deployed stack no longer puts exception details in error responses.** A
38
+ 500 from a stack whose `ENVIRONMENT` started with `dev` carried the exception
39
+ class, message and backtrace in the body. A deployed dev stack is as public as
40
+ prod, and that output hands a stranger file paths, gem versions and internal
41
+ messages. Inside Lambda the details now stay in the logs (`belt logs`) unless
42
+ the function sets `BELT_VERBOSE_ERRORS=true`. Outside Lambda (`belt server`,
43
+ specs) nothing changes: `dev*`, `local` and `test` are still verbose.
44
+ `BELT_VERBOSE_ERRORS=false` turns the details off everywhere. See UPGRADING.md.
45
+
46
+ ## 0.6.12
47
+
48
+ ### Security
49
+
50
+ - **An unsigned `Authorization: Bearer` token is no longer believed.** On a route
51
+ without an API Gateway authorizer, `Belt::Authentication::Claims.from_event`
52
+ base64-decoded the header token and returned its payload as the caller's
53
+ claims with no signature check, so a made-up token naming any `sub` and the
54
+ admin group made `current_user`, `cognito_admin?` and `authenticate_user!`
55
+ treat the caller as that user (and wrote the forged email, name and role to
56
+ their row). Header tokens are now verified by
57
+ `Belt::Authentication::TokenVerifier`: RS256 only, key by `kid` from the pool's
58
+ JWKS (cached per container), and `exp`, `iss`, `token_use == 'id'` and `aud`
59
+ all required. A token that can't be verified, including when no pool or
60
+ client id is configured, yields no claims. Routes behind `auth: :cognito`
61
+ were not affected and are unchanged. (Fizzy #2002)
62
+
63
+ ### Added
64
+
65
+ - `config.authentication.client_ids` (default: `COGNITO_CLIENT_ID`,
66
+ comma-separated): the app client ids a header token may be issued for.
67
+
68
+ ### Changed
69
+
70
+ - Apps that read `current_user` on a route with no authorizer must set
71
+ `COGNITO_USER_POOL_ID` and `COGNITO_CLIENT_ID` on the Lambda, or those
72
+ requests become anonymous. See UPGRADING.md.
73
+ - `Claims.decode` is unchanged (payload parsing, no signature check) but is no
74
+ longer used to establish identity.
75
+
3
76
  ## 0.6.11
4
77
 
5
78
  ### Added
data/README.md CHANGED
@@ -209,12 +209,13 @@ end
209
209
 
210
210
  **Key point:** `namespace` and `scope` are purely organizational — they affect URL paths and controller module resolution but never change which Lambda handles the request. Use `function` when you need routes to go to a different Lambda.
211
211
 
212
- **Per-route throttling:** any route or resource accepts `throttle: { rate:, burst: }` (steady-state requests per second plus the burst the token bucket absorbs). `belt routes -f json` emits it and the conveyor-belt provider (0.0.20+) applies it as API Gateway stage method settings. A route's `throttle` wins over the serving Lambda's `throttle:` in `config/lambda/<fn>.yml`, which in turn wins over the provider's stage-level `throttle` block.
212
+ **Per-route throttling:** any route, `resources`, `scope`, `namespace`, `function` or the `gateway` itself accepts `throttle: { rate:, burst: }` (steady-state requests per second plus the burst the token bucket absorbs). Routes inherit it from the nearest enclosing block; `throttle: false` opts a route out. `belt routes -f json` emits it and the conveyor-belt provider (0.0.20+) applies it as API Gateway stage method settings. A route-level `throttle` (including one inherited from the gateway) wins over the serving Lambda's `throttle:` in `config/lambda/<fn>.yml`, which in turn wins over the provider's stage-level `throttle` block. The limit is per route for all callers together, not per caller; `belt explain routing` has a WAF rate-rule recipe for per-IP limits.
213
213
 
214
214
  ```ruby
215
- gateway :api, auth: :none do
215
+ gateway :api, auth: :none, throttle: { rate: 50, burst: 100 } do
216
216
  post '/connect/chat', to: 'chat#create', throttle: { rate: 2, burst: 5 }
217
217
  resources :leads, only: [:create], throttle: { rate: 1, burst: 3 }
218
+ get '/health', to: 'health#show', throttle: false
218
219
  end
219
220
  ```
220
221
 
@@ -396,7 +397,8 @@ Belt::Observability::Metrics.track_event("OrderCreated", model: "Order")
396
397
 
397
398
  | Variable | Purpose |
398
399
  |----------|---------|
399
- | `ENVIRONMENT` | Controls verbose error responses (`dev*`, `local`, `test`) |
400
+ | `ENVIRONMENT` | Outside Lambda, `dev*`, `local`, `test` get verbose error responses |
401
+ | `BELT_VERBOSE_ERRORS` | `true` = verbose error responses on a deployed stack (off by default); `false` = off everywhere |
400
402
  | `BELT_METRICS_NAMESPACE` | CloudWatch metrics namespace (default: `Belt`) |
401
403
  | `ACTION` | Service name for logging (falls back to function name) |
402
404
  | `ERROR_NOTIFICATION_TOPIC_ARN` | SNS topic for error alerts |
@@ -11,13 +11,13 @@ module Belt
11
11
  #
12
12
  # 1. API Gateway Cognito authorizer — claims arrive pre-verified under
13
13
  # requestContext.authorizer.claims, with every value flattened to a String.
14
- # 2. A raw `Authorization: Bearer <id token>` header — the Lambda decodes it.
14
+ # 2. A raw `Authorization: Bearer <id token>` header, on a route with no
15
+ # authorizer — nothing has checked it, so TokenVerifier does: signature
16
+ # against the pool's JWKS, then expiry, issuer, token use and audience.
15
17
  #
16
- # Case 2 is signature-unverified by design: when a Cognito authorizer is attached,
17
- # the gateway has already checked the signature and an unsigned token never reaches
18
- # us. What we can still check cheaply is checked (structure, expiry, issuer, token
19
- # use), which is what stops an expired or foreign token from being waved through on
20
- # routes that read the header directly.
18
+ # A header token that can't be verified — forged, expired, foreign, or the app has
19
+ # no pool configured to verify against — is no identity at all. Unverified claims
20
+ # are never returned from #from_event.
21
21
  module Claims
22
22
  # Cognito sends `cognito:groups` as a JSON array in the raw token, but API
23
23
  # Gateway flattens it to a string — "[admins, members]" or "admins,members".
@@ -27,19 +27,19 @@ module Belt
27
27
 
28
28
  class << self
29
29
  # Claims for this request, or nil if there is no usable Cognito identity.
30
- def from_event(event, issuer: nil)
30
+ def from_event(event, issuer: nil, client_ids: nil)
31
31
  authorizer = event.dig('requestContext', 'authorizer', 'claims')
32
32
  return authorizer if authorizer
33
33
 
34
34
  token = bearer_token(event)
35
35
  return nil unless token
36
36
 
37
- decode(token, issuer: issuer)
37
+ TokenVerifier.verify(token, issuer: issuer, client_ids: client_ids)
38
38
  end
39
39
 
40
40
  # The raw Bearer credential, whatever it is. Callers that only want Cognito
41
- # tokens rely on #decode rejecting anything that isn't one — an app's own API
42
- # key scheme can share the header without special-casing here.
41
+ # tokens rely on TokenVerifier rejecting anything that isn't one — an app's own
42
+ # API key scheme can share the header without special-casing here.
43
43
  def bearer_token(event)
44
44
  header = authorization_header(event)
45
45
  return nil unless header&.start_with?('Bearer ')
@@ -53,9 +53,13 @@ module Belt
53
53
  headers['Authorization'] || headers['authorization']
54
54
  end
55
55
 
56
- # Decode a Cognito ID token's payload, rejecting it unless it is one.
57
- # Returns nil rather than raising: a bad token means "no identity", and every
58
- # caller here is deciding whether an identity exists.
56
+ # Parse a Cognito ID token's payload, rejecting it unless it is shaped like one.
57
+ #
58
+ # NOT an identity: the signature is not checked, so anyone can write a token
59
+ # that decodes. Use it only on a token something else has already verified.
60
+ # #from_event does not call this — it goes through TokenVerifier.
61
+ #
62
+ # Returns nil rather than raising for a token that doesn't parse.
59
63
  def decode(token, issuer: nil)
60
64
  payload = payload_segment(token)
61
65
  return nil unless payload
@@ -22,9 +22,12 @@ module Belt
22
22
  @user_class = nil
23
23
  @admin_groups = nil
24
24
  @issuer = nil
25
+ @client_ids = nil
25
26
  end
26
27
 
27
- attr_writer :admin_groups, :issuer
28
+ attr_writer :admin_groups, :issuer, :client_ids
29
+
30
+ alias client_id= client_ids=
28
31
 
29
32
  # Accepts a class or a name. Stored as a name and resolved on demand so the
30
33
  # setting can be declared before the model file is loaded.
@@ -52,9 +55,10 @@ module Belt
52
55
  configured.empty? ? DEFAULT_ADMIN_GROUPS : configured
53
56
  end
54
57
 
55
- # Expected `iss` claim. Derived from the Cognito env vars Belt's Terraform module
56
- # already exports, so apps don't restate it. Nil disables the issuer check —
57
- # which is the right behaviour locally and in tests, where there is no pool.
58
+ # Expected `iss` claim, and where the pool's signing keys are fetched from.
59
+ # Derived from COGNITO_USER_POOL_ID. Nil means there is no pool to verify a
60
+ # Bearer header token against, so such a token is never an identity. Routes
61
+ # behind an API Gateway authorizer don't need it.
58
62
  def issuer
59
63
  return @issuer if @issuer
60
64
 
@@ -64,6 +68,15 @@ module Belt
64
68
  region = ENV['COGNITO_REGION'] || ENV['AWS_REGION'] || 'us-east-1'
65
69
  "https://cognito-idp.#{region}.amazonaws.com/#{pool_id}"
66
70
  end
71
+
72
+ # App client ids a Bearer header token may be issued for (its `aud` claim).
73
+ # From COGNITO_CLIENT_ID, comma-separated when the pool has several clients
74
+ # (web and mobile, say). Empty means header tokens are never an identity.
75
+ def client_ids
76
+ return Array(@client_ids).map(&:to_s) if @client_ids
77
+
78
+ ENV.fetch('COGNITO_CLIENT_ID', '').to_s.split(',').map(&:strip).reject(&:empty?)
79
+ end
67
80
  end
68
81
  end
69
82
  end
@@ -31,12 +31,15 @@ module Belt
31
31
  Claims.bearer_token(event)
32
32
  end
33
33
 
34
- # The Cognito claims on this request, or nil if there aren't any. Memoized
35
- # including the nil, so a request decodes at most once.
34
+ # The Cognito claims on this request, or nil if there aren't any. Always
35
+ # verified: by the API Gateway authorizer, or — for a Bearer header on a route
36
+ # without one — by TokenVerifier against the pool's keys. Memoized including the
37
+ # nil, so a request verifies at most once.
36
38
  def cognito_claims
37
39
  return @cognito_claims if defined?(@cognito_claims)
38
40
 
39
- @cognito_claims = Claims.from_event(event, issuer: belt_authentication_config.issuer)
41
+ config = belt_authentication_config
42
+ @cognito_claims = Claims.from_event(event, issuer: config.issuer, client_ids: config.client_ids)
40
43
  end
41
44
 
42
45
  def cognito_sub
@@ -0,0 +1,136 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'base64'
4
+ require 'json'
5
+ require 'net/http'
6
+ require 'openssl'
7
+ require 'uri'
8
+
9
+ module Belt
10
+ module Authentication
11
+ # Verifies a Cognito ID token taken from an `Authorization: Bearer` header.
12
+ #
13
+ # A route with an API Gateway authorizer never needs this: the gateway checked the
14
+ # token and handed over the claims. A route without one has nothing in front of it,
15
+ # so a token there counts only if it was signed by the app's own pool, for one of
16
+ # the app's own clients. Everything is required — signature (RS256, key looked up
17
+ # by `kid` in the pool's JWKS), `exp`, `iss`, `token_use == 'id'` and `aud`.
18
+ #
19
+ # The key set is fetched once per Lambda container. An unknown `kid` triggers a
20
+ # refetch (Cognito rotates rarely), but at most once per REFETCH_INTERVAL, so a
21
+ # caller inventing key ids cannot make every request pay for an outbound call.
22
+ module TokenVerifier
23
+ ALGORITHM = 'RS256'
24
+ JWKS_TIMEOUT = 2
25
+ # Seconds before an unknown `kid` may trigger another fetch of a key set we hold.
26
+ REFETCH_INTERVAL = 60
27
+ # Seconds before retrying a fetch that failed outright.
28
+ RETRY_INTERVAL = 5
29
+
30
+ @key_sets = {}
31
+ @mutex = Mutex.new
32
+
33
+ class << self
34
+ # The verified claims, or nil. Never raises: a token that can't be verified
35
+ # means "no identity". Nil too when the issuer or client ids are unknown —
36
+ # without them there is nothing to verify against.
37
+ def verify(token, issuer:, client_ids:)
38
+ audiences = Array(client_ids).map(&:to_s).reject(&:empty?)
39
+ return nil if token.to_s.empty? || issuer.to_s.empty? || audiences.empty?
40
+
41
+ segments = token.to_s.split('.')
42
+ return nil unless segments.length == 3
43
+ return nil unless signed_by_pool?(segments, issuer)
44
+
45
+ claims = JSON.parse(decode_segment(segments[1]))
46
+ valid_claims?(claims, issuer, audiences) ? claims : nil
47
+ rescue StandardError
48
+ nil
49
+ end
50
+
51
+ # Test seam: supply a pool's keys ({ kid => OpenSSL::PKey::RSA }) so nothing
52
+ # is fetched.
53
+ def store_keys(issuer, keys)
54
+ @mutex.synchronize { @key_sets[issuer] = { keys: keys, fetch_after: monotonic_now + REFETCH_INTERVAL } }
55
+ end
56
+
57
+ def reset!
58
+ @mutex.synchronize { @key_sets = {} }
59
+ end
60
+
61
+ private
62
+
63
+ def signed_by_pool?(segments, issuer)
64
+ header = JSON.parse(decode_segment(segments[0]))
65
+ return false unless header.is_a?(Hash) && header['alg'] == ALGORITHM
66
+
67
+ key = key_for(header['kid'], issuer)
68
+ return false unless key
69
+
70
+ key.verify('SHA256', decode_segment(segments[2]), "#{segments[0]}.#{segments[1]}")
71
+ end
72
+
73
+ def valid_claims?(claims, issuer, audiences)
74
+ return false unless claims.is_a?(Hash)
75
+ return false unless claims['exp'].is_a?(Numeric) && claims['exp'] > Time.now.to_i
76
+ return false unless claims['iss'] == issuer
77
+ return false unless claims['token_use'] == 'id'
78
+
79
+ audiences.intersect?(Array(claims['aud']).map(&:to_s))
80
+ end
81
+
82
+ def key_for(kid, issuer)
83
+ return nil if kid.to_s.empty?
84
+
85
+ @mutex.synchronize do
86
+ set = @key_sets[issuer]
87
+ set = @key_sets[issuer] = fetch_key_set(issuer) if refetch?(set, kid)
88
+ set[:keys][kid]
89
+ end
90
+ end
91
+
92
+ def refetch?(set, kid)
93
+ return true if set.nil?
94
+
95
+ !set[:keys].key?(kid) && monotonic_now >= set[:fetch_after]
96
+ end
97
+
98
+ def fetch_key_set(issuer)
99
+ keys = fetch_keys(issuer)
100
+ { keys: keys || {}, fetch_after: monotonic_now + (keys ? REFETCH_INTERVAL : RETRY_INTERVAL) }
101
+ end
102
+
103
+ # The JWKS URL comes from the configured issuer, never from the token.
104
+ # Returns nil when the key set could not be fetched.
105
+ def fetch_keys(issuer)
106
+ uri = URI("#{issuer}/.well-known/jwks.json")
107
+ options = { use_ssl: uri.scheme == 'https', open_timeout: JWKS_TIMEOUT, read_timeout: JWKS_TIMEOUT }
108
+ response = Net::HTTP.start(uri.host, uri.port, **options) { |http| http.get(uri.request_uri) }
109
+ return nil unless response.is_a?(Net::HTTPSuccess)
110
+
111
+ JSON.parse(response.body).fetch('keys', []).each_with_object({}) do |jwk, keys|
112
+ keys[jwk['kid']] = rsa_key(jwk) if jwk['kty'] == 'RSA'
113
+ end
114
+ rescue StandardError
115
+ nil
116
+ end
117
+
118
+ # OpenSSL 3 keys are immutable, so build the PKCS#1 DER instead of setting n/e.
119
+ def rsa_key(jwk)
120
+ modulus = OpenSSL::BN.new(decode_segment(jwk['n']), 2)
121
+ exponent = OpenSSL::BN.new(decode_segment(jwk['e']), 2)
122
+ der = OpenSSL::ASN1::Sequence([OpenSSL::ASN1::Integer(modulus), OpenSSL::ASN1::Integer(exponent)]).to_der
123
+ OpenSSL::PKey::RSA.new(der)
124
+ end
125
+
126
+ def decode_segment(segment)
127
+ Base64.urlsafe_decode64(segment + ('=' * ((4 - (segment.length % 4)) % 4)))
128
+ end
129
+
130
+ def monotonic_now
131
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
132
+ end
133
+ end
134
+ end
135
+ end
136
+ end
@@ -3,6 +3,7 @@
3
3
  require_relative 'errors'
4
4
  require_relative 'configuration'
5
5
  require_relative 'authentication/configuration'
6
+ require_relative 'authentication/token_verifier'
6
7
  require_relative 'authentication/claims'
7
8
  require_relative 'authentication/cognito_authenticatable'
8
9
  require_relative 'authentication/model_macro'
@@ -13,6 +13,10 @@ module Belt
13
13
  'routes' => 'routing',
14
14
  'route' => 'routing',
15
15
  'router' => 'routing',
16
+ 'throttle' => 'routing',
17
+ 'throttling' => 'routing',
18
+ 'rate_limit' => 'routing',
19
+ 'waf' => 'routing',
16
20
  'controller' => 'controllers',
17
21
  'model' => 'models',
18
22
  'activeitem' => 'models',
@@ -114,6 +118,7 @@ module Belt
114
118
 
115
119
  Aliases:
116
120
  routes, route, router → routing
121
+ throttle, rate_limit, waf → routing
117
122
  controller → controllers
118
123
  model, activeitem → models
119
124
  deploy, terraform → deployment
@@ -0,0 +1,87 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative '../inflector'
4
+
5
+ module Belt
6
+ module CLI
7
+ # Which attributes a GSI copies from the base table. Shared by `belt setup tables`
8
+ # (reads `projection:` off a model's indexes() entry) and `belt g index`
9
+ # (reads `--projection`), so both write the same Terraform.
10
+ #
11
+ # A projection is nil (the default, ALL) or a hash:
12
+ # { type: 'KEYS_ONLY' }
13
+ # { type: 'INCLUDE', non_key_attributes: ['warnTurn'] }
14
+ module GsiProjection
15
+ TYPES = %w[ALL KEYS_ONLY INCLUDE].freeze
16
+
17
+ class Error < ArgumentError; end
18
+
19
+ module_function
20
+
21
+ # The `projection:` value inside one indexes() entry's options, as source text:
22
+ # projection: :keys_only
23
+ # projection: { include: %w[warnTurn] }
24
+ # Returns nil when the entry doesn't declare one.
25
+ def from_model_options(opts, index_name)
26
+ return nil unless opts.match?(/\bprojection:/)
27
+
28
+ if (match = opts.match(/\bprojection:\s*:?['"]?(\w+)['"]?/))
29
+ return build(match[1], [], index_name)
30
+ end
31
+
32
+ if (match = opts.match(/\bprojection:\s*\{\s*include:\s*(%w\[[^\]]*\]|\[[^\]]*\])\s*\}/))
33
+ return build('include', list_items(match[1]), index_name)
34
+ end
35
+
36
+ raise Error, "#{index_name}: can't read projection. Use projection: :keys_only, " \
37
+ ':all, or { include: %w[attrA attrB] }'
38
+ end
39
+
40
+ # `--projection keys_only`, `--projection all`, `--projection include:a,b`.
41
+ # Attribute names are camelCased like the CLI's --partition-key/--sort-key.
42
+ def from_cli(value, index_name)
43
+ type, attrs = value.to_s.split(':', 2)
44
+ attrs = attrs.to_s.split(',').map(&:strip).reject(&:empty?)
45
+ build(type, attrs.map { |a| Belt::Inflector.camelize_lower(a) }, index_name)
46
+ end
47
+
48
+ def build(type, attrs, index_name)
49
+ type = type.to_s.upcase
50
+ unless TYPES.include?(type)
51
+ raise Error, "#{index_name}: unknown projection #{type.downcase.inspect} " \
52
+ '(expected keys_only, all, or include)'
53
+ end
54
+ if type == 'INCLUDE' && attrs.empty?
55
+ raise Error, "#{index_name}: an include projection needs at least one attribute"
56
+ end
57
+ raise Error, "#{index_name}: only an include projection takes attributes" if type != 'INCLUDE' && attrs.any?
58
+
59
+ return nil if type == 'ALL'
60
+
61
+ type == 'INCLUDE' ? { type: type, non_key_attributes: attrs } : { type: type }
62
+ end
63
+
64
+ # HCL lines for the projection inside a global_secondary_index block. The blank
65
+ # line keeps `terraform fmt` from realigning the other arguments around the
66
+ # longer `non_key_attributes` name.
67
+ def hcl_lines(projection)
68
+ type = projection ? projection[:type] : 'ALL'
69
+ lines = [" projection_type = \"#{type}\""]
70
+ if projection && projection[:non_key_attributes]
71
+ attrs = projection[:non_key_attributes].map { |a| "\"#{a}\"" }.join(', ')
72
+ lines << ''
73
+ lines << " non_key_attributes = [#{attrs}]"
74
+ end
75
+ lines
76
+ end
77
+
78
+ def list_items(source)
79
+ if source.start_with?('%w')
80
+ source[3..-2].split
81
+ else
82
+ source[1..-2].scan(/['"]([^'"]+)['"]|:(\w+)/).map { |quoted, sym| quoted || sym }
83
+ end
84
+ end
85
+ end
86
+ end
87
+ end
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative 'tables_command'
4
+ require_relative 'gsi_projection'
4
5
  require_relative '../inflector'
5
6
 
6
7
  module Belt
@@ -28,6 +29,7 @@ module Belt
28
29
  def self.usage
29
30
  <<~USAGE
30
31
  Usage: belt generate index <table> <IndexName> --partition-key <key> [--sort-key <key>]
32
+ [--projection keys_only|all|include:attrA,attrB]
31
33
  belt destroy index <table> <IndexName>
32
34
 
33
35
  Add or remove a Global Secondary Index (GSI) from dynamodb.tf.
@@ -35,16 +37,22 @@ module Belt
35
37
  Examples:
36
38
  belt generate index messages ConversationIndex --partition-key conversation_id
37
39
  belt generate index messages RecentByUserIndex --partition-key user_id --sort-key created_at
40
+ belt generate index matches WarningIndex -p warn_due -s warn_at --projection keys_only
38
41
  belt destroy index messages ConversationIndex
39
42
 
43
+ --projection defaults to all. keys_only copies only the keys into the index;
44
+ include:a,b also copies the named attributes (DynamoDB names, e.g. warnTurn).
45
+ A narrower projection makes writes cheaper, but reading any other attribute
46
+ of a hit needs a GetItem on the table.
47
+
40
48
  Note: After modifying indexes, run `belt deploy` to apply changes to AWS.
41
49
  Adding a GSI to an existing table takes ~5-10 minutes (AWS limitation).
42
50
  USAGE
43
51
  end
44
52
 
45
53
  def self.add(args)
46
- table, index_name, partition_key, sort_key = parse_add_args(args)
47
- new(table, index_name, partition_key: partition_key, sort_key: sort_key).add
54
+ table, index_name, partition_key, sort_key, projection = parse_add_args(args)
55
+ new(table, index_name, partition_key: partition_key, sort_key: sort_key, projection: projection).add
48
56
  end
49
57
 
50
58
  def self.remove(args)
@@ -64,6 +72,7 @@ module Belt
64
72
  index_name = args.shift
65
73
  partition_key = nil
66
74
  sort_key = nil
75
+ projection = nil
67
76
 
68
77
  i = 0
69
78
  while i < args.length
@@ -74,6 +83,11 @@ module Belt
74
83
  when '--sort-key', '-s'
75
84
  i += 1
76
85
  sort_key = args[i]
86
+ when '--projection'
87
+ i += 1
88
+ projection = args[i] || abort('Error: --projection needs a value (keys_only, all, or include:a,b)')
89
+ when /\A--projection=(.*)\z/
90
+ projection = Regexp.last_match(1)
77
91
  end
78
92
  i += 1
79
93
  end
@@ -83,14 +97,23 @@ module Belt
83
97
  'Example: belt generate index messages ConversationIndex --partition-key conversation_id'
84
98
  end
85
99
 
86
- [table, index_name, partition_key, sort_key]
100
+ [table, index_name, partition_key, sort_key, parse_projection(projection, index_name)]
101
+ end
102
+
103
+ def self.parse_projection(value, index_name)
104
+ return nil if value.nil?
105
+
106
+ GsiProjection.from_cli(value, index_name)
107
+ rescue GsiProjection::Error => e
108
+ abort "Error: #{e.message}"
87
109
  end
88
110
 
89
- def initialize(table, index_name, partition_key: nil, sort_key: nil)
111
+ def initialize(table, index_name, partition_key: nil, sort_key: nil, projection: nil)
90
112
  @table = table
91
113
  @index_name = index_name
92
114
  @partition_key = partition_key
93
115
  @sort_key = sort_key
116
+ @projection = projection
94
117
  end
95
118
 
96
119
  def add
@@ -156,7 +179,7 @@ module Belt
156
179
  lines << " name = \"#{@index_name}\""
157
180
  lines << " hash_key = \"#{dynamo_pk}\""
158
181
  lines << " range_key = \"#{dynamo_sk}\"" if dynamo_sk
159
- lines << ' projection_type = "ALL"'
182
+ lines.concat(GsiProjection.hcl_lines(@projection))
160
183
  lines << ' }'
161
184
  lines.join("\n")
162
185
  end
@@ -134,7 +134,7 @@ module Belt
134
134
  end
135
135
 
136
136
  def inject_welcome_route!(routes, gateway)
137
- routes << {
137
+ welcome = {
138
138
  name: 'root',
139
139
  verb: 'GET',
140
140
  path: '/',
@@ -147,6 +147,8 @@ module Belt
147
147
  request_model: '',
148
148
  response_model: ''
149
149
  }
150
+ welcome[:throttle] = gateway.default_throttle if gateway.default_throttle
151
+ routes << welcome
150
152
  end
151
153
 
152
154
  def build_route_hash(route, gateway)
@@ -2,6 +2,7 @@
2
2
 
3
3
  require_relative 'env_resolver'
4
4
  require_relative 'terraform_command'
5
+ require_relative 'gsi_projection'
5
6
  require_relative '../inflector'
6
7
 
7
8
  module Belt
@@ -42,6 +43,8 @@ module Belt
42
43
  return unless validate!
43
44
 
44
45
  models = parse_models
46
+ return unless models
47
+
45
48
  if models.empty?
46
49
  puts "No models found in #{MODELS_DIR}/" unless @quiet
47
50
  return
@@ -75,6 +78,18 @@ module Belt
75
78
  .sort
76
79
 
77
80
  model_files.filter_map { |f| parse_model_file(f) }
81
+ rescue GsiProjection::Error => e
82
+ unreadable_model(e.message)
83
+ end
84
+
85
+ # A projection the generator can't read must not quietly become ALL — that's
86
+ # the silent revert this option exists to stop. Leave dynamodb.tf alone: abort
87
+ # an explicit run, and skip (don't kill the generator) on an auto-sync.
88
+ def unreadable_model(message)
89
+ abort "Error: #{message}" unless @quiet
90
+
91
+ puts " ⚠ skipped dynamodb.tf — #{message}"
92
+ nil
78
93
  end
79
94
 
80
95
  # Parse a model file to extract its name and index declarations.
@@ -90,7 +105,7 @@ module Belt
90
105
  model_name = Belt::Inflector.underscore(class_name)
91
106
 
92
107
  # Extract indexes() declaration
93
- indexes = extract_indexes(content)
108
+ indexes = extract_indexes(content, file_path)
94
109
 
95
110
  # cognito_authenticatable installs a GSI without an indexes() call
96
111
  indexes += extract_cognito_indexes(content)
@@ -113,7 +128,7 @@ module Belt
113
128
  match[1] ? Belt::Inflector.camelize_lower(match[1]) : match[2]
114
129
  end
115
130
 
116
- def extract_indexes(content)
131
+ def extract_indexes(content, file_path = nil)
117
132
  indexes = []
118
133
 
119
134
  # Match the indexes() DSL: indexes('Name' => { partition_key: 'pk' }, ...)
@@ -123,18 +138,26 @@ module Belt
123
138
 
124
139
  index_content = index_block[1]
125
140
 
126
- # Parse each index entry: 'IndexName' => { partition_key: 'key', sort_key: 'key' }
127
- index_content.scan(/'([^']+)'\s*=>\s*\{([^}]+)\}/) do |name, opts|
141
+ # Parse each index entry: 'IndexName' => { partition_key: 'key', sort_key: 'key' }.
142
+ # The options may hold one nested hash: projection: { include: %w[a b] }.
143
+ index_content.scan(/'([^']+)'\s*=>\s*\{((?:[^{}]|\{[^{}]*\})*)\}/) do |name, opts|
128
144
  partition_key = opts.match(/partition_key:\s*'([^']+)'/)&.captures&.first
129
145
  sort_key = opts.match(/sort_key:\s*'([^']+)'/)&.captures&.first
130
146
  next unless partition_key
131
147
 
132
- indexes << { name: name, partition_key: partition_key, sort_key: sort_key }
148
+ indexes << { name: name, partition_key: partition_key, sort_key: sort_key,
149
+ projection: model_projection(opts, name, file_path) }
133
150
  end
134
151
 
135
152
  indexes
136
153
  end
137
154
 
155
+ def model_projection(opts, index_name, file_path)
156
+ GsiProjection.from_model_options(opts, index_name)
157
+ rescue GsiProjection::Error => e
158
+ raise GsiProjection::Error, [file_path, e.message].compact.join(': ')
159
+ end
160
+
138
161
  # `cognito_authenticatable` installs an EmailIndex GSI without the model ever
139
162
  # calling indexes() — see Belt::Authentication::CognitoAuthenticatable. The
140
163
  # generator has to know that, or the table would be created without the GSI and
@@ -228,12 +251,37 @@ module Belt
228
251
  old_gsis = gsi_names(existing_content, label)
229
252
  new_gsis = gsi_names(new_content, label)
230
253
  dropped.concat((old_gsis - new_gsis).map { |gsi| "GSI \"#{gsi}\" on table \"#{label}\"" })
254
+ dropped.concat(reverted_projections(existing_content, new_content, label))
231
255
  dropped.concat(dropped_table_settings(existing_content, new_content, label))
232
256
  end
233
257
 
234
258
  dropped
235
259
  end
236
260
 
261
+ # A GSI hand-tuned to KEYS_ONLY or INCLUDE that the regen would put back to ALL.
262
+ # The index survives, so the name check above misses it, but every write to the
263
+ # table starts paying for the full copy again.
264
+ def reverted_projections(existing_content, new_content, label)
265
+ old_types = gsi_projection_types(existing_content, label)
266
+ new_types = gsi_projection_types(new_content, label)
267
+
268
+ old_types.filter_map do |gsi, type|
269
+ next if type == 'ALL' || new_types[gsi] != 'ALL'
270
+
271
+ "#{type} projection on GSI \"#{gsi}\" on table \"#{label}\" (would become ALL)"
272
+ end
273
+ end
274
+
275
+ # GSI name → projection_type for every GSI in the given table's block.
276
+ def gsi_projection_types(content, label)
277
+ block = table_block(content, label)
278
+ return {} unless block
279
+
280
+ block.scan(/global_secondary_index\s*\{([^}]*)\}/m).to_h do |(body)|
281
+ [body[/name\s*=\s*"([^"]+)"/, 1], body[/projection_type\s*=\s*"([^"]+)"/, 1]]
282
+ end
283
+ end
284
+
237
285
  # Nested blocks (`ttl`, `server_side_encryption`, …) and settings (`stream_enabled`,
238
286
  # …) a table has today that the regenerated table wouldn't. A hand-added ttl block
239
287
  # is the usual one — dropping it turns expiry off and rows quietly pile up.
@@ -346,8 +394,8 @@ module Belt
346
394
  puts "\n⚠ Regenerating #{dest} would DROP infrastructure not derived from your models:"
347
395
  dropped.each { |d| puts " • #{d}" }
348
396
  puts "\n This usually means a table, GSI, or setting (e.g. ttl) was added to dynamodb.tf by hand."
349
- puts ' Belt only tracks what it can read from lambda/models/*.rb (indexes, belongs_to,'
350
- puts ' cognito_authenticatable, ttl_attribute),'
397
+ puts ' Belt only tracks what it can read from lambda/models/*.rb (indexes and their'
398
+ puts ' projection:, belongs_to, cognito_authenticatable, ttl_attribute),'
351
399
  puts ' so a hand-added definition is invisible to the generator and gets overwritten.'
352
400
  end
353
401
 
@@ -430,7 +478,7 @@ module Belt
430
478
  lines << " name = \"#{idx[:name]}\""
431
479
  lines << " hash_key = \"#{idx[:partition_key]}\""
432
480
  lines << " range_key = \"#{idx[:sort_key]}\"" if idx[:sort_key]
433
- lines << ' projection_type = "ALL"'
481
+ lines.concat(GsiProjection.hcl_lines(idx[:projection]))
434
482
  lines << ' }'
435
483
  end
436
484
 
@@ -150,6 +150,7 @@ Belt.configure do |config|
150
150
  config.authentication.user_class = 'Account' # default: 'User'
151
151
  config.authentication.admin_groups = %w[staff] # default: ['admins'], or ADMIN_COGNITO_GROUPS
152
152
  config.authentication.issuer = '...' # default: derived from COGNITO_USER_POOL_ID
153
+ config.authentication.client_ids = %w[...] # default: COGNITO_CLIENT_ID (comma-separated)
153
154
  end
154
155
  ```
155
156
 
@@ -168,12 +169,46 @@ A route can be authenticated either way, and both are handled:
168
169
  1. **API Gateway Cognito authorizer** — claims arrive pre-verified under
169
170
  `requestContext.authorizer.claims`, with every value flattened to a string
170
171
  (`"true"`, `"[admins, members]"`).
171
- 2. **A raw `Authorization: Bearer <id token>` header** — the Lambda decodes it.
172
+ 2. **A raw `Authorization: Bearer <id token>` header**, on a route with no
173
+ authorizer — nothing has checked it, so Belt does.
172
174
 
173
- Case 2 is signature-unverified by design: where an authorizer is attached, the gateway
174
- already checked the signature and an unsigned token never reaches your code. What can
175
- still be checked cheaply is checked — structure, expiry, issuer, and `token_use` (an
176
- access token is rejected; it carries no email or name).
175
+ For case 2 Belt verifies the token itself and returns no claims unless every check
176
+ passes:
177
+
178
+ - signed with RS256 by a key in your pool's JWKS (looked up by `kid`, fetched once per
179
+ Lambda container)
180
+ - `exp` present and in the future
181
+ - `iss` is your pool
182
+ - `token_use` is `id` (an access token carries no email or name)
183
+ - `aud` is one of your app client ids
184
+
185
+ So a token someone made up is not an identity: `current_user` is nil,
186
+ `cognito_admin?` is false and `authenticate_user!` answers 401.
187
+
188
+ The Lambda needs to know the pool and the client to verify against. Add both to the
189
+ function's environment (`config/lambda/api.yml`):
190
+
191
+ ```yaml
192
+ env_vars:
193
+ COGNITO_USER_POOL_ID: ref(cognito_user_pool_id)
194
+ COGNITO_CLIENT_ID: ref(cognito_client_id) # comma-separated for several clients
195
+ ```
196
+
197
+ and supply the refs in `infrastructure/modules/app/main.tf`:
198
+
199
+ ```hcl
200
+ lambda_env_refs = merge(var.lambda_env_refs, {
201
+ cognito_user_pool_id = aws_cognito_user_pool.main.id
202
+ cognito_client_id = aws_cognito_user_pool_client.main.id
203
+ })
204
+ ```
205
+
206
+ Without them a header token is never believed — Belt fails closed rather than return
207
+ claims it could not verify. Routes declared `auth: :cognito` need neither variable:
208
+ the gateway has already done the checking.
209
+
210
+ `Belt::Authentication::Claims.decode` still parses a token's payload without checking
211
+ its signature. It is not an identity check; don't use it as one.
177
212
 
178
213
  Anything that isn't a Cognito ID token — including your own API key scheme sharing the
179
214
  same header — reads as "no Cognito identity" rather than an error, so
@@ -91,7 +91,8 @@ Belt::Observability::Metrics.track_event("OrderCreated", model: "Order")
91
91
 
92
92
  | Variable | Purpose |
93
93
  |----------|---------|
94
- | `ENVIRONMENT` | Controls error verbosity (`dev*`, `local`, `test` = verbose) |
94
+ | `ENVIRONMENT` | Outside Lambda, `dev*`, `local`, `test` = verbose error responses |
95
+ | `BELT_VERBOSE_ERRORS` | `true` = verbose error responses on a deployed stack (off by default); `false` = off everywhere |
95
96
  | `BELT_METRICS_NAMESPACE` | CloudWatch namespace (default: `Belt`) |
96
97
  | `ACTION` | Service name for logging |
97
98
  | `ERROR_NOTIFICATION_TOPIC_ARN` | SNS topic for error alerts |
@@ -91,6 +91,53 @@ Post.where(
91
91
  )
92
92
  ```
93
93
 
94
+ ### Declaring Indexes
95
+
96
+ `belt setup tables` writes `infrastructure/modules/app/dynamodb.tf` from your
97
+ models. Declare each GSI with `indexes(...)`, using DynamoDB attribute names:
98
+
99
+ ```ruby
100
+ class Match < ApplicationRecord
101
+ indexes(
102
+ 'PlayerIndex' => { partition_key: 'playerId', sort_key: 'createdAt' },
103
+ 'WarningIndex' => { partition_key: 'warnDue', sort_key: 'warnAt', projection: :keys_only },
104
+ 'TurnIndex' => { partition_key: 'turnDue', projection: { include: %w[warnTurn] } }
105
+ )
106
+ end
107
+ ```
108
+
109
+ Write lists with brackets (`%w[a b]`, `['a']`), not parentheses: the generator
110
+ reads `indexes(...)` as text and stops at the first `)`.
111
+
112
+ `projection:` picks which attributes DynamoDB copies into the index:
113
+
114
+ | Value | Terraform | Index holds |
115
+ |-------|-----------|-------------|
116
+ | omitted or `:all` | `projection_type = "ALL"` | the whole row |
117
+ | `:keys_only` | `projection_type = "KEYS_ONLY"` | table key (`id`) + index keys |
118
+ | `{ include: %w[a b] }` | `projection_type = "INCLUDE"` + `non_key_attributes` | keys + the listed attributes |
119
+
120
+ With `ALL`, every write to a row in the index rewrites its index copy, even when
121
+ no index key changed. A sparse index that only a sweep reads usually needs keys
122
+ only. The catch: a query on a `KEYS_ONLY` or `INCLUDE` index returns records with
123
+ just those attributes set. Read anything else with a `find` per hit:
124
+
125
+ ```ruby
126
+ Match.where(warn_due: 'Y', index: 'WarningIndex').each do |hit|
127
+ match = Match.find(hit.id) # GetItem for the full row
128
+ end
129
+ ```
130
+
131
+ Changing a projection on an existing table makes Terraform delete and rebuild
132
+ that GSI. Queries against it fail until the backfill finishes.
133
+
134
+ `belt generate index` takes the same choice: `--projection keys_only`,
135
+ `--projection all` (default), or `--projection include:warnTurn,seatId`.
136
+
137
+ If `dynamodb.tf` has a projection the models don't declare (a hand edit),
138
+ `belt setup tables` won't silently put it back to `ALL`: it asks first, and the
139
+ automatic sync after a generator skips the write.
140
+
94
141
  ### Count and Existence
95
142
 
96
143
  ```ruby
@@ -85,7 +85,8 @@ belt logs worker -e prod # specific environment
85
85
  | `BELT_METRICS_NAMESPACE` | CloudWatch metrics namespace (default: `Belt`) |
86
86
  | `ACTION` | Service name in log entries (falls back to function name) |
87
87
  | `ERROR_NOTIFICATION_TOPIC_ARN` | SNS topic for error alerts |
88
- | `ENVIRONMENT` | Controls verbose errors (`dev*`/`local`/`test` = verbose) |
88
+ | `ENVIRONMENT` | Outside Lambda (`belt server`, specs), `dev*`/`local`/`test` put the exception class, message and backtrace in error responses |
89
+ | `BELT_VERBOSE_ERRORS` | `true` puts those details in error responses on a deployed stack (off by default: a dev stack is public too); `false` turns them off everywhere |
89
90
 
90
91
  ## See Also
91
92
 
@@ -209,6 +209,152 @@ Declare which DynamoDB tables a route accesses (used by Terraform for IAM):
209
209
  resources :posts, tables: [:posts, :comments]
210
210
  ```
211
211
 
212
+ ## Throttling
213
+
214
+ Cap how many requests API Gateway lets through to a route with `throttle:`:
215
+ `rate` is the steady requests per second, `burst` is how many it absorbs at once.
216
+ Over the limit, callers get a `429` before the Lambda runs.
217
+
218
+ ```ruby
219
+ gateway :api, auth: :none, throttle: { rate: 50, burst: 100 } do # default for every route
220
+ post "/reports", to: "reports#create", throttle: { rate: 5, burst: 10 }
221
+ get "/health", to: "health#show", throttle: false # opt out of the default
222
+
223
+ scope path: "family", throttle: { rate: 1, burst: 2 } do # scope, namespace, function
224
+ resources :devices, only: [:create] # and nested resources inherit
225
+ end
226
+ end
227
+ ```
228
+
229
+ A route's own `throttle:` wins, then the nearest enclosing `scope` / `namespace` /
230
+ `function` / `resources` block, then the gateway's. `throttle: false` means "no
231
+ route-level throttle". `belt routes -f json` puts the result on each route, and the
232
+ conveyor-belt provider (0.0.20+) applies it as API Gateway stage method settings.
233
+
234
+ Where routes.rb sets no throttle, the provider falls back to the serving Lambda's
235
+ `throttle:` in `config/lambda/<fn>.yml`, then to the provider's stage-level
236
+ `throttle` block. Note that a **gateway-level default in routes.rb is a route-level
237
+ throttle**: it beats both of those. Use `throttle: false` on a route if the Lambda
238
+ YAML should decide it.
239
+
240
+ **Throttles are per route, not per caller.** API Gateway keeps one bucket per
241
+ route, shared by everyone. `throttle: { rate: 5, burst: 10 }` on `POST /reports`
242
+ stops a script from running up the bill, but that same script also uses up the
243
+ limit for real players. For per-caller limits (what Rails' controller
244
+ `rate_limit to:, within:` gives you), put a WAF rate-based rule in front of the
245
+ gateway (see below).
246
+
247
+ Throttling is approximate, so expect a few requests either side of the limit.
248
+ Method settings override the stage's `*/*` setting. Anything that throttles "the
249
+ whole stage" by patching only `*/*` (an emergency kill switch, for example) no
250
+ longer covers routes that have their own `throttle`. It has to patch those
251
+ method settings too, or cut Lambda concurrency instead.
252
+
253
+ ### Per-caller limits: WAF rate rule recipe
254
+
255
+ WAF counts requests per client IP over a window and blocks an IP that goes over.
256
+ Attach a REGIONAL web ACL to the gateway stage with the provider's
257
+ `waf_web_acl_arn`. WAF bills per web ACL, per rule and per million requests,
258
+ so one ACL with a few rules is the usual shape.
259
+
260
+ ```hcl
261
+ # infrastructure/modules/app/waf.tf
262
+ resource "aws_wafv2_web_acl" "api" {
263
+ name = "${var.app_name}-${var.environment}-api"
264
+ scope = "REGIONAL" # API Gateway stage; CLOUDFRONT scope is only for distributions (us-east-1)
265
+
266
+ default_action {
267
+ allow {}
268
+ }
269
+
270
+ # 20 POST /reports per IP per minute
271
+ rule {
272
+ name = "reports-per-ip"
273
+ priority = 1
274
+
275
+ action {
276
+ block {}
277
+ }
278
+
279
+ statement {
280
+ rate_based_statement {
281
+ limit = 20 # requests per window, minimum 10
282
+ evaluation_window_sec = 60 # 60, 120, 300 or 600
283
+ aggregate_key_type = "IP"
284
+
285
+ scope_down_statement {
286
+ and_statement {
287
+ statement {
288
+ byte_match_statement {
289
+ search_string = "/reports"
290
+ positional_constraint = "ENDS_WITH"
291
+ field_to_match {
292
+ uri_path {}
293
+ }
294
+ text_transformation {
295
+ priority = 0
296
+ type = "NONE"
297
+ }
298
+ }
299
+ }
300
+ statement {
301
+ byte_match_statement {
302
+ search_string = "POST"
303
+ positional_constraint = "EXACTLY"
304
+ field_to_match {
305
+ method {}
306
+ }
307
+ text_transformation {
308
+ priority = 0
309
+ type = "NONE"
310
+ }
311
+ }
312
+ }
313
+ }
314
+ }
315
+ }
316
+ }
317
+
318
+ visibility_config {
319
+ cloudwatch_metrics_enabled = true
320
+ metric_name = "reports-per-ip"
321
+ sampled_requests_enabled = true
322
+ }
323
+ }
324
+
325
+ visibility_config {
326
+ cloudwatch_metrics_enabled = true
327
+ metric_name = "${var.app_name}-${var.environment}-api"
328
+ sampled_requests_enabled = true
329
+ }
330
+ }
331
+ ```
332
+
333
+ ```hcl
334
+ resource "conveyor_belt" "main" {
335
+ # ...
336
+ waf_web_acl_arn = aws_wafv2_web_acl.api.arn
337
+ }
338
+ ```
339
+
340
+ - **Scope the rule down** to the routes that cost money (public writes). An
341
+ unscoped rule counts every request, including page loads and polling.
342
+ - **Key on `IP`.** That is the address that connected to whatever the ACL is
343
+ attached to. If clients call the gateway directly, attach a REGIONAL ACL to the
344
+ stage as above. If a CloudFront distribution sits in front of the API, a
345
+ regional ACL only sees CloudFront's edge addresses. Attach a `CLOUDFRONT`-scope
346
+ ACL (created in us-east-1) to the distribution instead, still keyed on `IP`.
347
+ Don't key on `X-Forwarded-For` (`FORWARDED_IP`): WAF takes the first address in
348
+ that header, and the client chooses it, so a script can rotate it to get around
349
+ the limit.
350
+ - **Watch the path WAF sees.** On the `execute-api` URL the path starts with the
351
+ stage name (`/dev/reports`), and on a custom domain it doesn't. `ENDS_WITH` matches
352
+ both.
353
+ - Try a new rule with `action { count {} }` first, check the CloudWatch metric, then
354
+ switch to `block {}`.
355
+ - Keep the route `throttle:` as well. WAF stops one noisy IP, and the throttle caps
356
+ the total when many IPs push at once.
357
+
212
358
  ## Inspecting Routes
213
359
 
214
360
  ```bash
@@ -108,7 +108,16 @@ module Belt
108
108
  Belt::HttpStatus.resolve(status)
109
109
  end
110
110
 
111
+ # Whether an error response carries the exception class, message and backtrace.
112
+ # A deployed stack is on the internet whatever it is called, so inside Lambda
113
+ # this is off unless BELT_VERBOSE_ERRORS=true. Outside Lambda (belt server,
114
+ # specs) it follows the environment name. BELT_VERBOSE_ERRORS=false turns it
115
+ # off everywhere. The details are always in the logs.
111
116
  def verbose_errors_enabled?
117
+ setting = ENV['BELT_VERBOSE_ERRORS'].to_s.strip.downcase
118
+ return setting == 'true' unless setting.empty?
119
+ return false if ENV.key?('AWS_LAMBDA_FUNCTION_NAME')
120
+
112
121
  env = ENV['ENVIRONMENT']&.downcase || ''
113
122
  env.start_with?('dev') || env == 'local' || env == 'test'
114
123
  end
@@ -30,9 +30,10 @@ module Belt
30
30
  # Per-route API Gateway limit: `throttle: { rate: 2, burst: 5 }` (requests per
31
31
  # second, token bucket). Emitted by `belt routes -f json` and applied by the
32
32
  # conveyor-belt provider (0.0.20+) as stage method settings; it wins over the
33
- # Lambda's `throttle:` in config/lambda/<fn>.yml. Returns nil when unset.
33
+ # Lambda's `throttle:` in config/lambda/<fn>.yml. Returns nil when unset or
34
+ # `false` (a route opting out of an inherited gateway/scope throttle).
34
35
  def self.normalize_throttle(raw)
35
- return nil if raw.nil?
36
+ return nil if raw.nil? || raw == false
36
37
 
37
38
  unless raw.is_a?(Hash)
38
39
  raise ArgumentError, "throttle must be a Hash like { rate: 2, burst: 5 } (got #{raw.inspect})"
@@ -116,7 +117,7 @@ module Belt
116
117
  inherited_controller: controller_name,
117
118
  inherited_lambda: @inherited_lambda,
118
119
  scope_module: @scope_module)
119
- nested_builder.instance_eval(&block)
120
+ @gateway.with_throttle(options) { nested_builder.instance_eval(&block) }
120
121
  end
121
122
 
122
123
  # Singular resource inside nested context (e.g. resource :billing inside resources :projects)
@@ -200,7 +201,7 @@ module Belt
200
201
  @inherited_tables = (@inherited_tables + Array(options[:tables] || [])).uniq
201
202
  @inherited_controller = options[:controller]&.to_s || @inherited_controller
202
203
 
203
- instance_eval(&) if block_given?
204
+ @gateway.with_throttle(options) { instance_eval(&) } if block_given?
204
205
 
205
206
  @prefix = previous_prefix
206
207
  @collection_prefix = previous_collection_prefix
@@ -415,7 +416,7 @@ module Belt
415
416
  end
416
417
 
417
418
  class ApiGateway
418
- attr_reader :name, :routes, :default_auth, :default_lambda, :default_cors, :default_tables
419
+ attr_reader :name, :routes, :default_auth, :default_lambda, :default_cors, :default_tables, :default_throttle
419
420
 
420
421
  def initialize(name, options = {})
421
422
  @name = name.to_s
@@ -424,7 +425,24 @@ module Belt
424
425
  @default_lambda = options[:lambda] || name
425
426
  @default_cors = options.fetch(:cors, true)
426
427
  @default_tables = Array(options[:tables] || [])
428
+ @default_throttle = Belt::Route.normalize_throttle(options[:throttle])
427
429
  @current_lambda_context = nil
430
+ @throttle_context = nil
431
+ end
432
+
433
+ # Runs the block with `options[:throttle]` as the throttle for every route it
434
+ # adds that doesn't set its own (scope, namespace, function, nested resources).
435
+ # `throttle: false` opts the block out of the gateway default.
436
+ def with_throttle(options)
437
+ return yield unless options.key?(:throttle)
438
+
439
+ previous = @throttle_context
440
+ @throttle_context = Belt::Route.normalize_throttle(options[:throttle]) || false
441
+ begin
442
+ yield
443
+ ensure
444
+ @throttle_context = previous
445
+ end
428
446
  end
429
447
 
430
448
  def lambda(name, &)
@@ -467,7 +485,7 @@ module Belt
467
485
  inherited_auth: inherited_auth,
468
486
  inherited_controller: inherited_controller,
469
487
  inherited_lambda: inherited_lambda)
470
- nested_builder.instance_eval(&)
488
+ with_throttle(options) { nested_builder.instance_eval(&) }
471
489
  end
472
490
 
473
491
  def resource(name, options = {})
@@ -521,12 +539,20 @@ module Belt
521
539
  request_model: options[:request_model],
522
540
  response_model: options[:response_model],
523
541
  response_context: options[:response_context],
524
- throttle: options[:throttle]
542
+ throttle: resolve_throttle(options)
525
543
  }
526
544
 
527
545
  @routes << Belt::Route.new(method, path, route_options)
528
546
  end
529
547
 
548
+ # Route's own `throttle:` (false opts out) → enclosing scope/resource block → gateway default.
549
+ def resolve_throttle(options)
550
+ return options[:throttle] if options.key?(:throttle)
551
+ return @throttle_context unless @throttle_context.nil?
552
+
553
+ @default_throttle
554
+ end
555
+
530
556
  def auto_infer_tables(resource_name, options)
531
557
  return options if options.key?(:tables)
532
558
 
@@ -678,7 +704,7 @@ module Belt
678
704
  @scope_tables = (@scope_tables + Array(options[:tables] || [])).uniq
679
705
  @scope_controller = options[:controller] || @scope_controller
680
706
 
681
- instance_eval(&) if block_given?
707
+ @gateway.with_throttle(options) { instance_eval(&) } if block_given?
682
708
 
683
709
  @scope_prefix = previous_prefix
684
710
  @scope_module = previous_module
@@ -712,7 +738,7 @@ module Belt
712
738
  @scope_auth = options[:auth] if options[:auth]
713
739
  @scope_tables = (@scope_tables + Array(options[:tables] || [])).uniq
714
740
 
715
- instance_eval(&) if block_given?
741
+ @gateway.with_throttle(options) { instance_eval(&) } if block_given?
716
742
 
717
743
  @lambda_target = previous_lambda
718
744
  @scope_auth = previous_auth
@@ -780,8 +806,8 @@ module Belt
780
806
  auth_override = options[:auth]
781
807
  route_definitions = mountable.respond_to?(:routes) ? mountable.routes : []
782
808
 
783
- route_definitions.each do |route_def|
784
- mount_route(route_def, prefix, extra_tables, auth_override)
809
+ @gateway.with_throttle(options) do
810
+ route_definitions.each { |route_def| mount_route(route_def, prefix, extra_tables, auth_override) }
785
811
  end
786
812
  end
787
813
 
@@ -913,7 +939,7 @@ module Belt
913
939
  inherited_auth: inherited_auth,
914
940
  inherited_controller: controller,
915
941
  inherited_lambda: @lambda_target)
916
- nested_builder.instance_eval(&)
942
+ @gateway.with_throttle(options) { nested_builder.instance_eval(&) }
917
943
  end
918
944
 
919
945
  def build_scoped_resource(name, options)
data/lib/belt/version.rb CHANGED
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Belt
4
- VERSION = '0.6.11'
4
+ VERSION = '0.6.13'
5
5
 
6
6
  # Ruby version new apps run on in Lambda. Rendered into the conveyor-belt
7
7
  # provider block (`ruby_version`) by `belt new` / `belt generate environment`.
@@ -58,9 +58,10 @@ belt apply <env>
58
58
  This creates: model, controller (with all CRUD actions), route entry, and DynamoDB schema.
59
59
 
60
60
  `infrastructure/modules/app/dynamodb.tf` is generated. Declare everything on the model:
61
- GSIs via `indexes(...)` / `belongs_to`, TTL via `ttl_attribute :expires_at`. Anything
62
- you add to the `.tf` by hand (a `ttl` block, a comment) gets dropped the next time it's
63
- regenerated.
61
+ GSIs via `indexes(...)` / `belongs_to` (with `projection: :keys_only` or
62
+ `projection: { include: %w[attr] }` for a narrower GSI), TTL via
63
+ `ttl_attribute :expires_at`. Anything you add to the `.tf` by hand (a `ttl` block, a
64
+ projection, a comment) gets dropped the next time it's regenerated.
64
65
 
65
66
  ### Add a model only (no API endpoint)
66
67
 
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: belt
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.6.11
4
+ version: 0.6.13
5
5
  platform: ruby
6
6
  authors:
7
7
  - Stowzilla
@@ -110,6 +110,7 @@ files:
110
110
  - lib/belt/authentication/configuration.rb
111
111
  - lib/belt/authentication/controller.rb
112
112
  - lib/belt/authentication/model_macro.rb
113
+ - lib/belt/authentication/token_verifier.rb
113
114
  - lib/belt/cli.rb
114
115
  - lib/belt/cli/apex_dns_sync.rb
115
116
  - lib/belt/cli/app_detection.rb
@@ -143,6 +144,7 @@ files:
143
144
  - lib/belt/cli/frontend_setup_command.rb
144
145
  - lib/belt/cli/generate_command.rb
145
146
  - lib/belt/cli/generator_registry.rb
147
+ - lib/belt/cli/gsi_projection.rb
146
148
  - lib/belt/cli/index_command.rb
147
149
  - lib/belt/cli/lambda_config_command.rb
148
150
  - lib/belt/cli/logs_command.rb