glacier-web-cli 0.3.0

Command-line tool for creating and running Glacier applications.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
---
title: Authentication and Authorisation
description: Signing users up, in and out with the authentication generator, protecting routes, checking permissions, throttling sign-in attempts, and working with an existing Rails app's passwords and tokens.
category: Going Further
order: 2
---

Glacier doesn't hide authentication inside the framework. A generator
writes sign up, sign in and sign out into your app as ordinary code, with
its tests, and the framework supplies only the parts that are easy to get
wrong: password hashing and session tokens.

After reading this guide, you will know:

- What `glacier generate authentication` writes, and how it works.
- How passwords and session tokens are stored.
- How to let only signed-in users reach a route.
- How to check what a signed-in user may do, with policies, and how to
  catch actions that don't check.
- How to limit sign-in attempts.
- How to authenticate an API with bearer tokens.
- How an existing Rails app's bcrypt passwords and JSON Web Tokens carry
  over.

The examples come from two apps. `accounts` is an HTML app with notes
that belong to the user who wrote them; `api` is a JSON API, described in
[Building JSON APIs](json_apis.html).

## Generating Authentication

In a new app, run the generator:

```sh
$ glacier generate authentication
      create  src/migrations/m20261004100420_create_users.rs
      update  src/migrations/mod.rs
      create  src/migrations/m20261004100421_create_sessions.rs
      update  src/migrations/mod.rs
      create  src/models/user.glacier
      create  src/models/session.glacier
      update  src/models/mod.rs
      update  src/models/mod.rs
      create  src/authentication.rs
      create  src/controllers/sessions_controller.glacier
      create  src/controllers/registrations_controller.glacier
      update  src/controllers/mod.rs
      update  src/controllers/mod.rs
      create  src/views/sessions/new.html
      create  src/views/registrations/new.html
      create  tests/factories/user.glacier
      create  tests/models/user.test.glacier
      create  tests/controllers/sessions_controller.test.glacier
      create  tests/controllers/registrations_controller.test.glacier
      update  tests/glacier.rs
      update  src/lib.rs
      update  src/routes.rs

Next: glacier db migrate. Routes for signed-in users go in a scope
through the `authenticated` pipeline:

    scope "/" through browser, authenticated {
        get "/account" => Accounts::show, as account;
    }

and `current_user(&ctx)` (alias Authentication.current_user) is who's signed in.
```

That's:

- `User` and `Session` models, and migrations for their tables.
- `src/authentication.rs`, which finds who is signed in on each request,
  and the middleware that keeps signed-out visitors away from a route.
- A sessions controller (sign in and out) and a registrations controller
  (sign up), with their pages.
- Tests for all of it, and a `User` factory, which gives each user it
  makes an email address of their own (see
  [Testing]testing.html#sequences).

It also registers the middleware in `src/lib.rs` and adds the routes. The
generator won't run in an app that already has a `User` or `Session`
model, `src/authentication.rs`, or either controller.

After `glacier db migrate`, `/registration/new` signs up and
`/session/new` signs in. The rest of this chapter walks through what was
written.

### Users

```glacier
model User do
  field email_address: String, required, unique
  field password_digest: String, protected
  # Set from a form or JSON, and stored only as password_digest.
  field password: Option<String>, virtual
  has_many :sessions

  # The user with this email address and password, if any. It takes as
  # long either way, so it doesn't reveal who has an account.
  def authenticate_by(email_address: &str, password: &str) -> Option<User> do
    user = User.find_by(email_address: User.normalize_email(email_address))!
    digest = user.as_ref().map(fn u -> u.password_digest.as_str() end)
    if glacier::auth::verify_password(password, digest) do
      user
    else
      None
    end
  end

  def normalize_email(email_address: &str) -> String do
    email_address.trim().to_lowercase()
  end

  validate do
    if self.password_digest.is_empty() and self.password.is_none() do
      errors.add("password", "can't be blank")
    end
    if self.password.as_ref().is_some_and(fn p -> p.chars().count() < 8 end) do
      errors.add("password", "is too short (minimum is 8 characters)")
    end
  end

  before_validation do
    self.email_address = User.normalize_email(&self.email_address)
  end

  before_save do
    if self.password.is_some() do
      self.password_digest = glacier::auth::hash_password(&self.password.take().unwrap_or_default())
    end
  end
end
```

`password` is a `virtual` field: it's set from the sign-up form but never
stored. `before_save` replaces it with its hash in `password_digest`. The
`validate` block requires a password for a new user and checks its
length. Email addresses are trimmed and lower-cased before validation, so
`" USER@example.com "` and `user@example.com` are the same account.

`password_digest` is `protected`, so it can't be set from params: a form
that sends `password_digest` is ignored, and only `password` changes it:

```glacier
test "ignores a password_digest sent as a param" do
  user = User.build([email_address: "new@example.com", password_digest: "not a hash"])
  refute user.save()!
  assert user.password_digest == ""
  assert user.errors_on("password") == ["can't be blank"]
end
```

`authenticate_by` finds the user and checks the password. When there's no
user with that email address, `glacier::auth::verify_password` still
spends the time of an Argon2 check, so for accounts with Argon2 passwords,
signing in takes about as long whether or not the email address has an
account. (Passwords imported from a Rails app are a different case; see
[Existing Rails Apps](#existing-rails-apps).)

### Sessions

Each sign-in is a row in `sessions`:

```glacier
model Session do
  field token_digest: String, required, unique, protected
  field user_agent: Option<String>
  belongs_to :user

  # Starts a session for the user, returning its token for the client. The
  # database keeps only the token's digest.
  def start(user_id: i64, user_agent: Option<String>) -> String do
    token = glacier::auth::new_token()
    session = Session.new(user_id: user_id, user_agent: user_agent, token_digest: glacier::auth::token_digest(&token))
    session.save()!
    token
  end

  # The session with this token, and its user.
  def find_by_token(token: &str) -> Option<Session> do
    Session.where(token_digest: glacier::auth::token_digest(token)).preload(:user).first()!
  end
end
```

```rust
use glacier::db::migration::*;

pub fn up(s: &mut Schema) {
    s.create_table("sessions", |t| {
        t.references("user").not_null().on_delete_cascade();
        // Only the token's digest: the token itself stays with the client.
        t.string("token_digest").not_null().unique();
        t.string("user_agent");
        t.timestamps();
    });
}

pub fn down(s: &mut Schema) {
    s.drop_table("sessions");
}
```

`Session.start` makes a new token for the client and stores only its
digest. `Session.find_by_token` digests the token a request sends and
looks that up, loading the user with it.

### Passwords and Tokens

The generated code relies on five functions in `glacier::auth`:

| Function | What it does |
| --- | --- |
| `hash_password(password)` | An Argon2id hash with a random 16-byte salt and the `argon2` crate's default cost (`m=19456,t=2,p=1`), as a PHC string (`$argon2id$v=19$m=19456,t=2,p=1$…`) |
| `verify_password(password, digest)` | Whether the password matches the digest; `digest` is an `Option`, and `None` still takes the time of a check |
| `new_token()` | 32 random bytes from the operating system, base64url-encoded (43 characters) |
| `token_digest(token)` | The token's SHA-256 digest, hex-encoded |
| `bearer_token(&ctx)` | The token from an `Authorization: Bearer …` header, if the request has one |

Only the digest of a session token is stored, so someone who reads the
`sessions` table can't use what they find there to sign in. The token
itself goes to the browser, inside the session cookie.

The generated `User` tests check the password half of this:

```glacier
test "stores only a hash of the password" do
  user = insert(User, email_address: "user@example.com")
  assert user.password_digest.starts_with("$argon2id$")
  assert user.password.is_none()
end

test "signs in with the right password only" do
  insert(User, email_address: "user@example.com")
  assert User.authenticate_by("user@example.com", "password")!.is_some()
  assert User.authenticate_by(" USER@example.com ", "password")!.is_some()
  assert User.authenticate_by("user@example.com", "wrong")!.is_none()
  assert User.authenticate_by("nobody@example.com", "password")!.is_none()
end

test "needs a password of 8 characters or more" do
  user = User.build(params_for(User, password: "short"))
  refute user.save()!
  assert user.errors_on("password") == ["is too short (minimum is 8 characters)"]
end

test "email addresses are unique, whatever their case" do
  insert(User, email_address: "user@example.com")
  user = User.build(params_for(User, email_address: "User@Example.com"))
  refute user.save()!
  assert user.errors_on("email_address") == ["has already been taken"]
end
```

### Signing Up, In and Out

The controllers are short, because the work is in the models and
`src/authentication.rs`:

```glacier
alias Authentication.start_session

controller Registrations do
  def new do
    render user: User.new(), title: "Sign up"
  end

  def create(ctx) do
    user = User.build(ctx.params())
    if user.save()! do
      start_session(&ctx, &user)!
      redirect "/", notice: "Welcome!"
    else
      render :new, user, title: "Sign up", status: 422
    end
  end
end
```

```glacier
alias Authentication.start_session
alias Authentication.end_session
alias Authentication.after_sign_in_path

controller Sessions do
  def new do
    render email_address: "", alert: "", title: "Sign in"
  end

  def create(ctx) do
    params = ctx.params()
    email_address = params.get("email_address").unwrap_or_default()
    password = params.get("password").unwrap_or_default()
    case User.authenticate_by(email_address, password)! do
      Some(user) ->
        start_session(&ctx, &user)!
        redirect after_sign_in_path(&ctx), notice: "Signed in."
      None ->
        alert = "Try another email address or password."
        render :new, email_address: email_address, alert: alert, title: "Sign in", status: 422
    end
  end

  def destroy(ctx) do
    end_session(&ctx)!
    redirect new_session_path(), notice: "Signed out."
  end
end
```

A wrong email address and a wrong password get the same message, so the
sign-in page doesn't reveal which accounts exist. The sign-up page does: an
email address that's already registered gets "has already been taken". The routes go through the
`browser` pipeline, so the forms are protected against CSRF:

```rust
scope "/" through browser {
    get "/session/new" => Sessions::new, as new_session;
    post "/session" => Sessions::create, as session;
    delete "/session" => Sessions::destroy;
    get "/registration/new" => Registrations::new, as new_registration;
    post "/registration" => Registrations::create, as registration;
}
```

## Who's Signed In

`src/authentication.rs` is the core of it. The `Authentication`
middleware runs on every request: it reads a token from an
`Authorization: Bearer` header or, failing that, from the session cookie,
and if a session has that token, it stores the session and its user in
the request:

```rust
/// Finds each request's session, from the session cookie or a bearer token.
/// Register it on the app, so every page knows who's signed in.
pub struct Authentication;

impl Middleware for Authentication {
    fn handle(&self, mut ctx: Context, next: Next) -> BoxFuture<Response> {
        Box::pin(async move {
            let token = match glacier::auth::bearer_token(&ctx) {
                Some(token) => Some(token.to_owned()),
                None => ctx.session().get::<String>(SESSION_TOKEN),
            };
            if let Some(token) = token
                && let Ok(Some(session)) = Session::find_by_token(&token).await
                && let Some(user) = session.user.get().cloned()
            {
                ctx.extensions_mut().insert(Current { user, session });
            }
            next.run(ctx).await
        })
    }
}
```

The generator registers it on the app in `src/lib.rs`:

```rust
// Who's signed in, for every request.
.middleware(authentication::Authentication)
```

`current_user(&ctx)` gives the signed-in user, if there is one:

```rust
/// The signed-in user and their session, found by [`Authentication`].
#[derive(Clone)]
pub struct Current {
    pub user: User,
    pub session: Session,
}

/// The signed-in user, if there is one.
pub fn current_user(ctx: &Context) -> Option<&User> {
    ctx.extensions().get::<Current>().map(|current| &current.user)
}
```

Signing in and out happens in two functions the controllers call:

```rust
/// Signs `user` in: a new session, with its token in the browser's session
/// cookie. Returns the token too, for API clients.
pub async fn start_session(ctx: &Context, user: &User) -> glacier::Result<String> {
    let user_agent = ctx.header("user-agent").map(str::to_owned);
    let token = Session::start(user.id, user_agent).await?;
    ctx.session().insert(SESSION_TOKEN, &token)?;
    Ok(token)
}

/// Signs out: ends the current session, however its token was sent.
pub async fn end_session(ctx: &Context) -> glacier::Result<()> {
    if let Some(current) = ctx.extensions().get::<Current>() {
        current.session.clone().destroy().await?;
    }
    ctx.session().remove(SESSION_TOKEN);
    Ok(())
}
```

The browser's session cookie is encrypted, `HttpOnly`, `SameSite=Lax`,
and `Secure` in production. It has no expiry date, so the browser usually
drops it when it closes, but the row in `sessions` stays until the user signs
out.

WARNING: Sessions don't expire. The generated code has no time limit on a
session token, so a token stays valid until its session row is deleted,
which only signing out (or deleting the user) does. Signing out ends only
the current session, and changing the password leaves the user's other
sessions valid. If your app needs sessions to expire, check
the session's `inserted_at` in `Session.find_by_token`.

## Protecting Routes

The generator adds an `authenticated` pipeline to `src/routes.rs`:

```rust
// Only for signed-in users; see src/authentication.rs.
pipeline authenticated = Pipeline::new().with(RequireAuthentication);
```

and routes that only signed-in users may reach go in a scope through it,
after `browser`:

```rust
scope "/" through browser, authenticated, authorized {
    resources "/notes" => Notes;
    get "/account" => Accounts::show, as account;
}
```

(The `authorized` pipeline is covered in
[Authorisation](#catching-a-missing-authorize).)

`RequireAuthentication` lets a signed-in request through. Anyone else is
sent to sign in, or, if the request looks like an API client's (it has a
bearer token, or its `Accept` header asks for JSON), answered with
`401 Unauthorized`:

```rust
/// Lets only signed-in users through. A browser is sent to sign in, and
/// back here afterwards; an API client gets `401 Unauthorized`.
pub struct RequireAuthentication;

impl Middleware for RequireAuthentication {
    fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
        Box::pin(async move {
            if ctx.extensions().get::<Current>().is_some() {
                return next.run(ctx).await;
            }
            let api = glacier::auth::bearer_token(&ctx).is_some()
                || ctx
                    .header("accept")
                    .is_some_and(|accept| accept.contains("application/json"));
            if api {
                return Error::new(StatusCode::UNAUTHORIZED, "sign in first").into_response();
            }
            if *ctx.method() == Method::GET {
                let _ = ctx.session().insert(RETURN_TO, ctx.uri().to_string());
            }
            Response::redirect(&crate::routes::new_session_path())
        })
    }
}
```

For a `GET`, it remembers the page in the session, and after signing in,
`after_sign_in_path` sends the browser back there:

```rust
/// Where to go after signing in: the page that sent the browser to sign in,
/// or the home page.
pub fn after_sign_in_path(ctx: &Context) -> String {
    let path = ctx.session().get::<String>(RETURN_TO);
    ctx.session().remove(RETURN_TO);
    path.unwrap_or_else(|| "/".to_owned())
}
```

The notes tests check the whole round trip:

```glacier
test "sends a signed-out visitor to sign in, and back afterwards" do
  res = get "/notes"
  assert res.status == :see_other
  assert res.location == "/session/new"

  user = insert(User)
  get res.location
  res = post "/session", [email_address: &user.email_address, password: "password"]
  assert res.location == "/notes"
end
```

### The Signed-In User in an Action

Inside the `authenticated` scope, `current_user(&ctx)` is always `Some`.
The `accounts` app adds a small function to `src/authentication.rs` that
turns it into a `Result`, so an action can use `?`:

```rust
/// The signed-in user, for actions behind the `authenticated` pipeline,
/// which has already sent everyone else to sign in.
pub fn signed_in_user(ctx: &Context) -> glacier::Result<&User> {
    current_user(ctx).ok_or_else(|| Error::new(StatusCode::UNAUTHORIZED, "sign in first"))
}
```

`create` uses it to give a new note its owner. The `user_id` is set after
`Note.build(ctx.params())`, so a `user_id` sent with the form can't make
the note someone else's:

```glacier
def create(ctx) do
  user = signed_in_user(&ctx)?
  authorize NotePolicy.create(user)
  note = Note.build(ctx.params())
  # Whoever is signed in, never a user_id sent with the form.
  note.user_id = user.id
  if note.save()! do
    redirect note, notice: "Note created."
  else
    render :new, note, title: "New note", status: 422
  end
end
```

```glacier
test "creates a note for the signed-in user" do
  user = sign_in()
  other = insert(User)
  res = post "/notes", params_for(Note, user_id: other.id)
  assert res.status == :see_other
  assert get(res.location).body =~ "Note created."
  assert Note.first()!.unwrap().user_id == user.id
end
```

`update` needs the same care. `note.update(ctx.params())` would accept a
`user_id` from the form, so a user could hand their note to someone else.
Glacier can't mark a `belongs_to` key `protected` yet, so the action
leaves `user_id` out of the params with `without` before updating:

```glacier
def update(ctx) do
  note = Note.find(ctx.id()?)!
  authorize NotePolicy.update(signed_in_user(&ctx)?, &note)
  # A note keeps its owner, whatever user_id the form sends.
  if note.update(ctx.params().without("user_id"))! do
    redirect note, notice: "Note updated."
  else
    render :edit, note, title: "Edit note", status: 422
  end
end
```

```glacier
test "keeps a note's owner when the form sends another user_id" do
  user = sign_in()
  other = insert(User)
  note = insert(Note, user_id: user.id)
  res = patch note, params_for(Note, user_id: other.id), title: "Mine"
  assert res.status == :see_other
  assert Note.find(note.id)!.user_id == user.id
end
```

## Authorisation

Signing in says who someone is; authorisation says what they may do.
The rules are your app's own code, and `authorize` checks them in an
action.

### Policies

By convention, the rules for a model go in a policy, one per model. The
generator writes one, once the app has a `User` model (it refuses to run
without `src/models/user.glacier` or `user.rs`, which `glacier generate
authentication` writes):

```sh
$ glacier generate policy Note
      create  src/services/note_policy.glacier
      create  src/services/mod.rs
      update  src/lib.rs

Next: decide each rule in src/services/note_policy.glacier, then `authorize NotePolicy.show(user, note)`
in the actions. Add `VerifyAuthorized` to a pipeline to catch actions that forget.
```

A policy is a `service` (see [The .glacier
Language](glacier_language.html)) with a rule for each of `index`,
`show`, `create`, `update` and `destroy` (`new` and `edit` use `create` and
`update`). Each takes the user, and the
rules for one record take the record too. The generator writes every rule
as `false`, so nothing is allowed until you decide, with its arguments
named `_user` and `_note` so that the stubs build without warnings. In
the `accounts` app, any signed-in user may list and write notes, and only
a note's own user may see, change or delete it:

```glacier
# Who may do what with notes: any signed-in user may list and write
# notes, and only a note's own user may see, change or delete it.
service NotePolicy do
  # Whether the user may list them.
  def index(_user: &User) -> bool do
    true
  end

  # Whether the user may see one.
  def show(user: &User, note: &Note) -> bool do
    note.user_id == user.id
  end

  # Whether the user may make one.
  def create(_user: &User) -> bool do
    true
  end

  # Whether the user may change this one.
  def update(user: &User, note: &Note) -> bool do
    note.user_id == user.id
  end

  # Whether the user may delete this one.
  def destroy(user: &User, note: &Note) -> bool do
    note.user_id == user.id
  end
end
```

A rule is an ordinary function, so a test can call it directly:

```glacier
test "lets only a note's own user change it" do
  user = insert(User)
  other = insert(User)
  note = insert(Note, user_id: user.id)
  assert NotePolicy.update(&user, &note)
  refute NotePolicy.update(&other, &note)
  refute NotePolicy.destroy(&other, &note)
end
```

### Checking With `authorize`

`authorize` in an action answers `403 Forbidden` unless the rule allows
it. A controller brings the policy in with `alias Services.NotePolicy`:

```glacier
controller Notes do
  def index(ctx) do
    user = signed_in_user(&ctx)?
    authorize NotePolicy.index(user)
    notes = Note.where(user_id: user.id).order(inserted_at: :desc)!
    render notes, title: "Notes"
  end

  def show(ctx) do
    note = Note.find(ctx.id()?)!
    authorize NotePolicy.show(signed_in_user(&ctx)?, &note)
    render note, title: "Note"
  end
```

`authorize` takes any `bool` expression, so a policy is a convention
rather than a requirement: a method on the model, or a check written in
place, works the same way. It compiles to a call to `glacier::authorize`,
which returns an error with status 403 when the expression is false, and
`?` returns it from the action. In a controller written in Rust, call
`glacier::authorize(allowed)?` yourself.

Lists need their own filter, as `index` does with
`where(user_id: user.id)`, because `authorize` checks one thing at a time:
`NotePolicy.index(user)` says whether the user may list notes at all, not
which notes they see.

```glacier
describe "someone else's note" do
  setup do
    sign_in()
  end

  test "can't be seen" do
    other = insert(User)
    note = insert(Note, user_id: other.id)
    assert get(note).status == :forbidden
  end

  test "can't be deleted" do
    other = insert(User)
    note = insert(Note, user_id: other.id)
    assert delete(note).status == 403
    assert Note.count()! == 1
  end
end
```

### Catching a Missing `authorize`

An action that never calls `authorize` is open to every user who can reach
it. `glacier::middleware::VerifyAuthorized` catches that: on a pipeline,
it checks each request's action once it has answered. The `accounts` app
adds a pipeline for it to the notes routes:

```rust
// Every action here must `authorize` (or `skip_authorization`).
pipeline authorized = Pipeline::new().with(VerifyAuthorized);
```

```rust
scope "/" through browser, authenticated, authorized {
    resources "/notes" => Notes;
    get "/account" => Accounts::show, as account;
}
```

When the action answers with a status below 400 and neither `authorize`
nor `skip_authorization` was called while handling the request,
`VerifyAuthorized` logs an error naming the method and path. Outside
production it also replaces the response with `500 Internal Server
Error`; in production the response goes out unchanged. Which one applies
is set by the `GLACIER_ENV` variable, and an app without it counts as
development, so a production server must set `GLACIER_ENV=production`. An error response
(`4xx` or `5xx`) passes through, so a note that isn't found is still a
`404`. Routes outside the pipeline aren't checked.

Removing the `authorize` line from `destroy` makes both `destroy` tests
fail; this is the one for someone else's note:

```text
---- controllers::notes_controller::someone_else_s_note::can_t_be_deleted stdout ----

thread '<unnamed>' (12897264) panicked at tests/controllers/notes_controller.test.glacier:135:5:
assertion failed: delete(note).status == 403
  left:  :internal_server_error (500)
  right: 403
```

WARNING: `VerifyAuthorized` finds a missing `authorize` in development
and in tests; it doesn't protect anything in production. It checks only
after the action has run, so whatever the action did, such as deleting
someone else's note here, has already happened by the time the response
is replaced, and in production the response isn't replaced at all. It
checks only that `authorize` was called, allowed or not, not that the
rule or the record was the right one, and it doesn't check that a list is
filtered. It's a net for tests that request every action, not a
replacement for `authorize`.

`skip_authorization`, on a line of its own in an action
(`glacier::skip_authorization()` in Rust), marks an action as having
nothing to authorize. Every signed-in user may see their own account
page, so the `accounts` app's `Accounts.show` skips:

```glacier
controller Accounts do
  # Every signed-in user may see their own account, so there's nothing to
  # authorize.
  def show(ctx) do
    skip_authorization
    email_address = signed_in_user(&ctx)?.email_address.clone()
    render email_address: email_address, title: "Account"
  end
end
```

```glacier
test "shows the signed-in user their account" do
  user = insert(User)
  get "/session/new"
  post "/session", [email_address: &user.email_address, password: "password"]
  res = get "/account"
  assert res.status == :ok
  assert res.body =~ format!("Signed in as {}.", user.email_address)
end
```

Pipelines run in the order a scope lists them, so `authorized` comes after
`authenticated`. The other way round, the redirect that sends a
signed-out visitor to sign in is checked too: it isn't an error response
and no action authorized it, so outside production it becomes a `500`,
and in production each one logs an error.

## Throttling Sign-In Attempts

`glacier::middleware::Throttle` limits how often something can happen. It
takes a name
(for the log), a limit, a period, and a function that picks the key to
count a request under, or `None` to leave the request alone. The
`accounts` app counts sign-in attempts per email address:

```rust
// At most 5 sign-in attempts a minute for each email address.
.middleware(Throttle::new("sign-in", 5, Duration::from_secs(60), |ctx| {
    let signing_in = *ctx.method() == Method::POST && ctx.path() == "/session";
    let email = ctx.params().get("email_address")?.trim().to_lowercase();
    signing_in.then_some(email)
}))
```

Over the limit, the answer is `429 Too Many Requests` with the body
`Retry later`, until the period's window ends:

```glacier
test "allows 5 sign-in attempts a minute for each email address" do
  insert(User, email_address: "user@example.com")
  for _ in 0..5 do
    res = post "/session", [email_address: "user@example.com", password: "wrong"]
    assert res.status == :unprocessable_entity
  end
  res = post "/session", [email_address: "user@example.com", password: "password"]
  assert res.status == :too_many_requests
  res = post "/session", [email_address: "other@example.com", password: "password"]
  assert res.status == :unprocessable_entity
end
```

Some details to know:

- Requests are counted in fixed windows of the period (each minute, here),
  not a sliding one, so up to twice the limit can get through around the
  boundary between two windows.
- Counts are kept in memory, in each process. Several processes or
  servers each count separately, and a restart starts afresh.
- The period must be at least a second, and is counted in whole seconds.
- Registered on the app with `.middleware(…)`, as here, a throttle runs
  before routing, for every request. It can go in a pipeline instead,
  with `Pipeline::new().with(Throttle::new(…))`, to cover only that
  pipeline's routes.

### Client IP Addresses

To throttle by client instead, use `ctx.remote_ip()`. It's the address of the connection, unless that
is a trusted proxy, in which case it's the nearest address in the
`X-Forwarded-For` header that isn't one (or the first address in it, if
they all are; or the connection's address, if the header is missing). Trusted proxies are loopback and
private network addresses (`127.0.0.0/8`, `10.0.0.0/8`, `172.16.0.0/12`,
`192.168.0.0/16`, `::1` and `fc00::/7`); the list can't be configured yet.

`remote_ip()` returns `None` when there's no connection, which is the case
in tests, so a throttle keyed on it counts nothing in tests.

## Authenticating an API

`glacier generate authentication --api` writes the same models, with
controllers that speak JSON and clients that send their token in an
`Authorization: Bearer` header instead of a cookie. In an app made with
`glacier new --api`, which has no pages, plain `glacier generate
authentication` writes this flavour too; `--api` is for an app that also
has pages, as the `api` app does:

```sh
$ glacier generate authentication --api
      create  src/migrations/m20261004100423_create_users.rs
      update  src/migrations/mod.rs
      create  src/migrations/m20261004100424_create_sessions.rs
      update  src/migrations/mod.rs
      create  src/models/user.glacier
      create  src/models/session.glacier
      update  src/models/mod.rs
      update  src/models/mod.rs
      create  src/authentication.rs
      create  src/controllers/sessions_controller.glacier
      create  src/controllers/registrations_controller.glacier
      update  src/controllers/mod.rs
      update  src/controllers/mod.rs
      create  tests/factories/user.glacier
      create  tests/models/user.test.glacier
      create  tests/controllers/sessions_controller.test.glacier
      create  tests/controllers/registrations_controller.test.glacier
      update  tests/glacier.rs
      update  src/lib.rs
      update  src/routes.rs

Next: glacier db migrate. Routes for signed-in users go in a scope
through the `authenticated` pipeline:

    scope "/" through api, authenticated {
        get "/account" => Accounts::show, as account;
    }

and `current_user(&ctx)` (alias Authentication.current_user) is who's signed in.
```

The `User` and `Session` models are the same. Signing in returns the
token, with `201 Created`; signing out answers `204 No Content`:

```glacier
alias Authentication.start_session
alias Authentication.end_session

controller Sessions do
  # Signs in, returning the token to send as `Authorization: Bearer <token>`.
  def create(ctx) do
    params = ctx.params()
    email_address = params.get("email_address").unwrap_or_default()
    password = params.get("password").unwrap_or_default()
    case User.authenticate_by(email_address, password)! do
      Some(user) ->
        token = start_session(&ctx, &user)!
        json [token: token], status: :created
      None ->
        json [error: "Try another email address or password."], status: :unauthorized
    end
  end

  def destroy(ctx) do
    end_session(&ctx)!
    head :no_content
  end
end
```

```glacier
alias Authentication.start_session

controller Registrations do
  # Signs up and signs in, returning the token as `Sessions` does.
  def create(ctx) do
    user = User.build(ctx.params())
    if user.save()! do
      token = start_session(&ctx, &user)!
      json [token: token], status: :created
    else
      json user.errors_json(), status: :unprocessable_entity
    end
  end
end
```

`src/authentication.rs` reads only the bearer token, and
`RequireAuthentication` always answers `401 Unauthorized`:

```rust
//! Signing in and out, and who's signed in. Written by `glacier generate
//! authentication`; it's your code now, so change it as you need.
//!
//! A session is a row in `sessions`. The client gets its token when it
//! signs in and sends it as `Authorization: Bearer <token>`. The database
//! stores only the token's SHA-256 digest.

use glacier::handler::BoxFuture;
use glacier::prelude::*;

use crate::models::{Session, User};

/// The signed-in user and their session, found by [`Authentication`].
#[derive(Clone)]
pub struct Current {
    pub user: User,
    pub session: Session,
}

/// The signed-in user, if there is one.
pub fn current_user(ctx: &Context) -> Option<&User> {
    ctx.extensions().get::<Current>().map(|current| &current.user)
}

/// Finds each request's session from its bearer token. Register it on the
/// app, so every request knows who's signed in.
pub struct Authentication;

impl Middleware for Authentication {
    fn handle(&self, mut ctx: Context, next: Next) -> BoxFuture<Response> {
        Box::pin(async move {
            let token = glacier::auth::bearer_token(&ctx).map(str::to_owned);
            if let Some(token) = token
                && let Ok(Some(session)) = Session::find_by_token(&token).await
                && let Some(user) = session.user.get().cloned()
            {
                ctx.extensions_mut().insert(Current { user, session });
            }
            next.run(ctx).await
        })
    }
}

/// Lets only signed-in users through; others get `401 Unauthorized`.
pub struct RequireAuthentication;

impl Middleware for RequireAuthentication {
    fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
        Box::pin(async move {
            if ctx.extensions().get::<Current>().is_some() {
                return next.run(ctx).await;
            }
            Error::new(StatusCode::UNAUTHORIZED, "sign in first").into_response()
        })
    }
}

/// Signs `user` in: a new session, whose token the client sends from now on.
pub async fn start_session(ctx: &Context, user: &User) -> glacier::Result<String> {
    let user_agent = ctx.header("user-agent").map(str::to_owned);
    Session::start(user.id, user_agent).await
}

/// Signs out: ends the current session.
pub async fn end_session(ctx: &Context) -> glacier::Result<()> {
    if let Some(current) = ctx.extensions().get::<Current>() {
        current.session.clone().destroy().await?;
    }
    Ok(())
}
```

The routes go through an `api` pipeline, which the generator adds if the
app doesn't have one: it renders errors as JSON and has no CSRF check,
because API clients send a token rather than a cookie.

In tests, `glacier::testing::bearer(token)` sends the token with every
later request, as a client that has signed in would:

```glacier
test "signs in, returning a token" do
  insert(User, email_address: "user@example.com")
  res = post "/session", [email_address: "user@example.com", password: "password"]
  assert res.status == :created
  assert res.body =~ "\"token\":"
  assert Session.count()! == 1
end

test "rejects a wrong password" do
  insert(User, email_address: "user@example.com")
  res = post "/session", [email_address: "user@example.com", password: "wrong"]
  assert res.status == :unauthorized
  assert Session.count()! == 0
end

test "signs out the session whose token is sent" do
  user = insert(User, email_address: "user@example.com")
  token = Session.start(user.id, None)!
  glacier::testing::bearer(&token)
  res = delete "/session"
  assert res.status == :no_content
  assert Session.count()! == 0
end
```

A page on another origin that calls the API from a browser needs the API
to allow that origin, with `glacier::middleware::Cors` (see
[Cross-Origin Requests](json_apis.html#cross-origin-requests)). A bearer
token isn't a cookie, so the browser sends it only when the page's script
adds it, and the API doesn't need CORS credentials for it.

## Existing Rails Apps

### Devise and `has_secure_password` Passwords

Devise and `has_secure_password` store bcrypt hashes (`$2a$…`).
`glacier::auth::verify_password` recognises them and checks them as
bcrypt, so the generated `User.authenticate_by` signs in users whose
passwords a Rails app hashed, without changes. New and changed passwords
are hashed with Argon2id. The hash in this test was made by Ruby's
`bcrypt` gem:

```glacier
test "signs in a user whose password Devise hashed with bcrypt" do
  # Ruby's BCrypt::Password.create("secret", cost: 4), as Devise and
  # has_secure_password store it.
  digest = "$2a$04$KJY25RprEuJvbxVtp0EL6OAwC3ZAHpva.goKBL6bcCq6/HLxIEkUu"
  user = User.new(email_address: "devise@example.com", password_digest: digest)
  assert user.save()!

  assert User.authenticate_by("devise@example.com", "secret")!.is_some()
  assert User.authenticate_by("devise@example.com", "wrong")!.is_none()
end
```

WARNING: Checking a bcrypt hash takes as long as its cost makes it, and
Devise's default cost of 12 is much slower than Glacier's Argon2 check. So
while users still have bcrypt hashes, response times can show which email
addresses belong to them. A bcrypt hash isn't replaced with an Argon2 one
when its user signs in; it changes only when the password does.

To use an existing `users` table, the `User` model's fields must match
its columns: Devise's column is `encrypted_password` and its email column
is `email`, where the generator uses `password_digest` and
`email_address`.

### JSON Web Tokens

`glacier::auth::jwt` signs and checks JSON Web Tokens signed with
HMAC-SHA256 (`HS256`), as Rails apps using Ruby's `jwt` gem issue them,
so a Glacier app can accept tokens a Rails app issued, and the other way
round:

- `jwt::encode(&claims, secret)` returns a token for the claims (a JSON
  object), with the header `{"alg":"HS256"}` and the claims' keys in
  order. The token in this test is byte for byte the one Ruby's `jwt` gem
  makes for the same claims and secret.
- `jwt::decode(token, secret)` checks the signature, in constant time, and
  the `exp` claim if there is one, and returns the claims. `exp` must be a
  whole number of seconds (anything else is malformed), and a token is
  expired from that second on, with no allowance for clock skew.

```glacier
test "reads a token signed by the Rails app's jwt gem" do
  # Ruby: JWT.encode({user_id: 1, email: "a@b.c", exp: 4102444800}, "s", "HS256")
  token = "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJlbWFpbCI6ImFAYi5jIiwiZXhwIjo0MTAyNDQ0ODAwfQ.6DVTKEZh7vTr7ohSSxZEV8iyMg6REQCYy7-nCjR3oVk"
  claims = glacier::auth::jwt::decode(token, b"s").unwrap()
  assert claims["user_id"] == 1
  assert claims["email"] == "a@b.c"

  assert glacier::auth::jwt::encode(&claims, b"s") == token
  assert glacier::auth::jwt::decode(token, b"another secret").is_err()
end
```

`decode` fails with a `JwtError`: `Malformed`, `Algorithm` (the header
isn't `HS256`), `Signature` or `Expired`. It checks nothing else: not
`nbf`, `iat`, `iss` or `aud`, so check any of those your app relies on in
the claims it returns. Other algorithms, such as RS256, aren't supported.

## What Isn't Built Yet

Many apps need more than the generator writes. Glacier doesn't have
these yet:

- Password resets and email confirmation (they need mailers, which
  Glacier doesn't have yet), magic links and "remember me".
- Expiring sessions (see the warning above).
- A check that an action filtered a list to what the user may see;
  `VerifyAuthorized` checks only that `authorize` was called.
- A configurable list of trusted proxies for `remote_ip()`.