chiark / gitweb /
Testing: Provide incrementing url
[cgi-auth-flexible.git] / caf.pod
1 # -*- fundamental -*-
2
3 =head1 NAME
4
5 CGI::Auth::Flexible - web authentication optionally using cookies
6
7 =head1 SYNOPSYS
8
9  my $verifier = CGI::Auth::Flexible->new_verifier(setting => value,...);
10  my $authreq = $verifier->new_request($cgi);
11
12  # simple applications
13  $authreq->check_ok() or return;
14
15  # sophisticated applications
16  my $divert_kind = $authreq->check_divert();
17  if ($divert_kind) { ... print diversion page and quit ... }
18
19  # while handling the request
20  $user = $authreq->get_username();
21  $authreq->check_mutate();
22
23 =head1 DESCRIPTION
24
25 CGI::Auth::Flexible is a library which you can use to add a
26 forms/cookie-based login facility to a Perl web application.
27
28 CGI::Auth::Flexible doesn't interfere with your application's URL path
29 namespace and just needs a few (configurable) form parameter and
30 cookie name(s) for its own use.  It tries to avoid making assumptions
31 about the implementation structure of your application.
32
33 Because CGI::Auth::Flexible is licenced under the AGPLv3, you will
34 probably need to provide a facility to allow users (even ones not
35 logged in) to download the source code for your web app.  Conveniently
36 by default CGI::Auth::Flexible provides (for pure Perl webapps) a
37 mechanism for users to get the source.
38
39 CGI::Auth::Flexible is designed to try to stop you accidentally
40 granting access by misunderstanding the API.  (Also it, of course,
41 guards against cross-site scripting.)  You do need to make sure to
42 call CGI::Auth::Flexible before answering AJAX requests as well as
43 before generating HTML pages, of course, and to call it in every
44 entrypoint to your system.
45
46 =head2 CHECKLIST
47
48 As a minimum you need to do all of the things on this checklist, where
49 applicable.  The items marked SECURITY are the ones that you might
50 forget: without them your application may appear to work, but will be
51 insecure.
52
53 =over
54
55 =item *
56
57 Call C<new_verifier> (once at application startup)
58
59 =item *
60
61 Call C<new_request> (once per request)
62
63 =item *
64
65 B<SECURITY>: Call C<check_ok> or C<check_divert> on every request, and
66 honour the return value.
67
68 =item *
69
70 If you're using C<check_ok>, implement either the
71 C<username_password_error> or C<login_ok> hook and provide it as
72 a setting to C<new_verifier>.
73
74 =item *
75
76 Provide the setting C<dir> (or provide absolute paths for all the
77 other relevant settings).
78
79 =item *
80
81 Call C<get_username> when you need to know who's logged in.
82
83 =item *
84
85 B<SECURITY>: Call C<check_mutate> or C<mutate_ok>, if you specified
86 C<promise_check_mutate>.
87
88 =item *
89
90 B<SECURITY>: Call C<check_nonpage> for every request which is not a page load
91 (if your application has any of those).
92
93 =item *
94
95 When generating URLs and forms (including AJAX requests), include the
96 hidden form parameter using C<secret_hidden_val> or
97 C<secret_hidden_html> when appropriate (see below).
98
99 =item *
100
101 B<SECURITY>: If you do not override the source provision facility (see
102 L</SOURCE CODE DOWNLOAD>), check that the assumptions it makes aren't
103 going to leak security-critical data.
104
105 =item *
106
107 Set up HTTPS on your webserver, or set the C<encrypted_only> setting
108 to a false value.
109
110 =back
111
112 These points will now be covered in more detail.
113
114 =head2 INITIALISATION
115
116 Your application should, on startup (eg, when it is loaded by
117 mod_perl) do
118 C<< $verifier = CGI::Auth::Flexible->new_verifier(settings...) >>.
119 This call can be expensive and is best amortised.
120
121 The resulting verifier object can be used to process individual
122 requests, in each case with
123 C<< $authreq = CGI::Auth::Flexible->new_request($cgi) >>.
124
125 See L</SETTINGS>.
126
127 =head2 CHECKING AND RESPONSE GENERATION
128
129 If the user is logged in, your application is to handle the request.
130 Otherwise, the user needs to be presented with a login form or error
131 message, as appropriate.  CGI::Auth::Flexible provides two alternative
132 interfaces for this:
133
134 =head3 Simple applications
135
136 The simplist usage is to call C<< $request->check_ok() >> which will
137 check the user's authentication.  If the user is not logged in it will
138 generate a login form (or redirection or other appropriate page) and
139 return false; your application should not then processing that request
140 any further.  If the user is logged in it will return true.
141
142 Various hooks are provided to customise the responses generated by
143 C<check_ok>.
144
145 After C<check_ok> returns true you should go ahead and process the
146 request; you can use C<< $request->get_username >> to find out which
147 user the request came from.
148
149 =head2 Sophisticated applications
150
151 If you want to handle the control flow and to generate login forms,
152 redirections, etc., yourself, you can say
153 C<< $divert = $request->check_divert >>.  This returns undef if
154 the user is logged in, or I<divert spec> if some kind of login
155 page or diversion should be generated.  See L</DIVERT SPEC> below for
156 details of how to deal with the return value.
157
158 =head2 MUTATING OPERATIONS AND EXTERNAL LINKS
159
160 =head3 Mutation-ignorant applications
161
162 By default CGI::Auth::Flexible does not permit external links into
163 your site.  All GET requests give a "click to continue" page which
164 submits a form which loads your app's main page.  In this
165 configuration all your application's forms and AJAX requests should
166 use C<POST>.  This restriction arises from complicated deficiencies
167 in the web's security architecture.
168
169 Such applications are also not able to provide user-specific CSS
170 stylesheets, javascript, favicons, etc.
171
172 =head3 Mutation-aware applications
173
174 The alternative is for your application to always make a special check
175 when the incoming request is going to do some kind of action (such as
176 modifying the user's setup, purchasing goods, or whatever) rather than
177 just retrieve and/or display information.  We term such requests
178 "mutating" requests.
179
180 Then non-mutating pages can be linked to from other, untrustworthy,
181 websites.
182
183 To support external links, and C<GET> requests, pass
184 C<< promise_check_mutate => 1 >> in I<settings>, and then call
185 C<< $authreq->check_mutate() >> before taking any actions.  If the
186 incoming request is not suitable then C<< $authreq->check_mutate() >>
187 will call C<die>.
188
189 There have to be no mutating C<GET> requests in your application (but
190 you shouldn't have any of those anyway); if there are, they won't
191 work.  (CGI::Auth::Flexible will spot them and cause them to fail,
192 rather than allow them to be insecure.)
193
194 =head2 GENERATING URLS, FORMS AND AJAX QUERIES
195
196 When you generate a URL, C<POST> form or AJAX request you may need to
197 include a secret hidden form parameter for the benefit of
198 CGI::Auth::Generic.  This form parameter will be checked by
199 C<check_ok>/C<check_divert> and should be ignored by your application.
200
201 By default the hidden parameter is called C<caf_assochash>.
202
203 After calling C<check_ok> or C<check_divert> the value to put in your
204 form can be obtained from C<secret_hidden_val>; C<secret_hidden_html>
205 will generate the whole HTML C<< <input...> >> element.
206
207 =head3 Mutation-ignorant applications
208
209 For mutation-ignorant applications (see above), all forms etc. should
210 include the hidden parameter (and as discussed, they must all use
211 POST rather than GET).
212
213 =head3 Mutation-aware applications
214
215 For mutation-aware applications, whether to include the secret
216 parameter depends on the kind of request.  CGI::Auth::Flexible knows
217 when it is necessary.  You should find out by calling
218 C<need_add_hidden>.
219
220 If it is inconvenient to call C<need_add_hidden> at runtime, you can
221 rely instead on the following promises:  All POST requests (which
222 includes all mutating requests) need the parameter.  The return value
223 of need_add_hidden depends only on the $method and $reqtype
224 parameters, so you can query it once and remember the answer.
225 HTML page load GETs do not need the parameter.  It is better to
226 err on the side of including the parameter.
227
228 If you really must, you can call C<need_add_hidden> "on the bench"
229 during development and bake the answer into your application code
230 structure.  However, if you do that and a new vulnerability was
231 discovered which is fixed by changing the answer, updating
232 CGI::Auth::Flexible wouldn't be sufficient to fix it.
233
234 =head3 Mutation-aware applications - non-page requests
235
236 If your mutation-aware application supports non-page resources (AJAX
237 and JSON requests, stylesheets, favicons, etc.) it must inform
238 CGI::Auth::Flexible when it is handling such a request, by calling
239 C<check_nonpage>.
240
241 Normally C<check_nonpage> will simply return (and you can ignore the
242 return value).  However, if there is an attack (or, perhaps, a bug) it
243 will die, stopping the attack.
244
245 (You do not need to call C<check_nonpage> for POST requests, but it is
246 harmless to do so.)
247
248 =head3 Mutation-aware applications - novel kinds of request
249
250 If you want to support a kind of request perhaps not yet known about
251 by CGI::Auth::Flexible, you can provide information about that new
252 request kind using C<update_get_need_add_hidden>.
253
254 =head2 DATA STORAGE
255
256 CGI::Auth::Flexible needs to store various information in plain files;
257 it does this in the directory specified by the C<dir> parameter.
258
259 =head1 SOURCE CODE DOWNLOAD
260
261 By default, CGI::Auth::Flexible provides a facility for users to
262 download the source code for the running version of your web
263 application.
264
265 This facility makes a number of important assumptions which you need
266 to check.  Note that if the provided facility is not sufficient
267 because your application is more sophisticated than it copes with (or
268 if you disable the builtin facility), you may need to implement a
269 functioning alternative to avoid violating the AGPLv3 licence.
270
271 Here are the most important (default) assumptions:
272
273 =over
274
275 =item *
276
277 Your app's source code is available by looking at @INC, $0 and
278 S<$ENV{'SCRIPT_FILENAME'}> (the B<source items>).  See
279 C<srcdump_listitems>.  Where these point to files or directories under
280 revision control, the source item is the whole containing vcs tree.
281
282 =item *
283
284 Specifically, there are no compiled or autogenerated Perl
285 files, Javascript resources, etc., which are not contained in one of
286 the source item directories.  (Files which came with your operating
287 system install don't need to be shipped as they fall under the system
288 library exception.)
289
290 =item *
291
292 You have not installed any modified versions of system
293 libraries (including system-supplied Perl modules) in C</usr> outside
294 C</usr/local>.  See C<srcdump_system_dir>.
295
296 =item *
297
298 For each source item in a dvcs, the entire dvcs history does
299 not contain anything confidential (or libellous).  Also, all files which
300 contain secrets are in the dvcs's I<.ignore> file.  See
301 C<srcdump_vcsscript_git> et al.
302
303 =item *
304
305 For each source item NOT in a dvcs, there are no confidential
306 files with the world-readable bit set (being in a world-inaccessible
307 directory is not sufficient).  See C<srcdump_excludes>.
308
309 =item *
310
311 You have none of your app's source code in C</etc>.
312
313 =item *
314
315 You don't regard pathnames on your server as secret.
316
317 =item *
318
319 You don't intentionally load Perl code by virtue of C<.>
320 being in C<@INC> by default.  (See C<srcdump_filter_cwd>.)
321
322 =back
323
324 =head1 MAIN FUNCTIONS AND METHODS
325
326 =over
327
328 =item C<< CGI::Auth::Flexible->new_verifier(setting => value, ...) >>
329
330 Initialises an instance and returns a verifier object.
331 The arguments are setting pairs like a hash initialiser.
332 See L</SETTINGS> below.
333
334 =item C<< $verifier->new_request($cgi) >>
335
336 Prepares to process a request.  I<$cgi> should normally
337 be the query object from L<CGI(3perl)>.  Most of the default
338 hook methods assume that it is; however if you replace enough of
339 the hook methods then you can pass any value you like and it
340 will be passed to your hooks.
341
342 The return value is the authentication request object (I<$authreq>)
343 which is used to check the incoming request and will contain
344 information about its credentials.
345
346 =item C<< $authreq->check_divert() >>
347
348 Checks whether the user is logged in.  Returns undef if the user is
349 logged in and we should service the request.  Otherwise returns a
350 divert spec (see L</DIVERT SPEC>) saying what should happen instead.
351
352 This method may die if it doesn't like the request, in which case
353 the request needs to be rejected.
354
355 =item C<< $authreq->check_ok() >>
356
357 Checks whether the user is logged in.  Returns true if the user is
358 logged in and we should service the request.
359
360 Otherwise it handles the request itself, generating any appropriate
361 redirect, login form, or continuation page.  It then returns false and
362 the application should not process the request further.
363
364 =item C<< $verifier->disconnect() >>
365
366 Discards the resources (open files, etc.) in the verifier object.
367
368 =back
369
370 =head1 REQUEST-RELATED FUNCTIONS AND METHODS
371
372 All of these are only valid after C<check_divert> or C<check_ok> has
373 been called.  (In the case of C<check_ok> it won't normally be sensible
374 to call these functions unless C<check_ok> returned true.)
375
376 =item C<< $authreq->get_divert() >>
377
378 Returns the value previously returned by C<check_divert>.
379
380 =item C<< $authreq->get_username() >>
381
382 Returns the name of the logged-in user.  If the user was not logged
383 in (or their session had timed out, or something), returns undef.
384
385 =item C<< $authreq->check_mutate() >>
386
387 Declares to CGI::Auth::Generic that the request being handled will
388 "mutate".  That is, it will modify some server-side state (eg, adding
389 items to shopping baskets, posting messages to blogs, sending emails,
390 or whatever).
391
392 If you have set the setting C<promise_check_mutate> you must call
393 C<check_mutate> whenever appropriate.  If you haven't then it's
394 irrelevant.  See L<MUTATING OPERATIONS AND EXTERNAL LINKS>.
395
396 C<check_mutate> will either return successfully, indicating that all
397 is well and the request should proceed, or it will die.  If it dies
398 that means that the request was improper, which can only result from a
399 bug or an attack.  So an "internal server error" is a suitable
400 response.
401
402 =item C<< $authreq->check_nonpage($method, $reqtype) >>
403
404 Declares to CGI::Auth::Generic that the request is not a page request,
405 but rather a request of type I<$reqtype>.
406
407 If your application has set the setting C<promise_check_mutate>,
408 whenever it is handling anything except an HTML page loads, it must
409 call this function.  See L</REQUEST TYPES>, and
410 L<GENERATING URLS, FORMS AND AJAX QUERIES>.
411
412 C<check_nonpage> will either return successfully, indicating that all
413 is well and the request should proceed, or it will die, like
414 C<check_mutate>.
415
416 =head1 RESPONSE-RELATED FUNCTIONS AND METHODS
417
418 =item C<< $authreq->url_with_query_params($params, [$nonpagetype]) >>
419
420 Convenience function which returns a url for a GET request to this
421 application.
422
423 I<$params> is a hashref specifying the parameters and the PATH_INFO
424 (not including any parameters related to CGI::Auth::Flexible).
425 The keys are the parameter names, and the values are array refs with
426 the parameter value(s) (as strings, as yet unquoted).  (They are array
427 refs because it is possible to pass multiple values for the same
428 parameter in a single request; normally each arrayref would be a
429 singleton.)
430
431 The request path will be the path to the application.  If a parameter
432 with name C<< '' >> is supplied, it is taken as the PATH_INFO - its
433 value will be appended to the application path.  (It should normally
434 start with C<< / >>, and only one value should be supplied.)
435
436 =item C<< something->need_add_hidden($method, $reqtype) >>
437
438 Enquires whether a request of type I<$reqtype> using HTTP method
439 I<$method> needs the hidden form parameter.  See L</REQUEST TYPES>.
440
441 =item C<< something->secret_hidden_val() >>
442
443 Returns the value of the hidden form parameter.  This should be
444 included in all POST requests to your application (and thus be a
445 hidden form parameter in all forms).
446
447 It should also be in some (maybe all) GET requests.  If your
448 application is mutation-ignorant, it should be in all GET requests.
449 If you are mutation-aware, you need to consult C<need_add_hidden>.
450
451 The name of the hidden parameter is the setting C<assoc_param_name>,
452 C<caf_hassochash> by default.  xxx rename param and setting
453
454 =item C<< something->secret_hidden_html() >>
455
456 Returns the HTML for an C<INPUT> element specifying the hidden form
457 parameter.
458
459 =item C<< something->secret_cookie_val() >>
460
461 Returns the value of the secret cookie.  CGI::Auth::Flexible sets this
462 cookie in the forms generated by C<check_ok>.  You may also set it
463 yourself (and indeed you must do so if you use C<check_divert>).
464
465 item C<< $authreq->_chain_params() >>
466
467 Returns a hash of the "relevant" parameters to this request, in a form
468 suitable for C<url_with_query_params>.  This is all of the query
469 parameters which are not related to CGI::Auth::Flexible.  The
470 PATH_INFO from the request is returned as the parameter C<< '' >>.
471
472 =back
473
474 =head1 OTHER FUNCTIONS AND METHODS
475
476 =over
477
478 =item C<< $verifier_or_authreq->hash($data) >>
479
480 Hashes the supplied data using the hash function specified by the
481 C<hash_algorithm> setting, and converts the result to a string of hex
482 digits.
483
484 =item C<< something->update_get_need_add_hidden($reqtype, $value, [$force]) >>
485
486 Updates CGI::Auth::Generic's knowledge about the various kinds of
487 request, and whether they need the hidden form parameter.  This
488 function applies only to GET requests - POST requests always use the
489 parameter.
490
491 I<$reqtype> is the request type (the value which will be passed to
492 C<check_nonpage> and C<need_add_hidden>.  If you are supporting a new
493 I<$reqtype> you shouuld coordinate with CGI::Auth::Flexible upstrea,
494 or other users, to assign a unique request type name.
495
496 This method may be called on an authreq or a verifier, in which case
497 it will affect all authreqs using the same verifier.  Or it may be
498 called on the class as a whole, in which case it will affect the
499 global default list for all verifiers.
500
501 If I<$force> is supplied and true, this will override
502 CGI::Auth::Flexible's existing knowledge.  Otherwise this new setting
503 will be ignored if CGI::Auth::Flexible already knows about the request
504 type.  (When called on a verifier or authreq, it will ignore the
505 update in favour of existing knowledge recorded both globally in the
506 class or due to previous requests on the same verifier.)
507
508 See L</REQUEST TYPES>.
509
510 =item C<< CGI::Auth::Flexible::srcdump_dir_cpio($cgi,$verifier,$dumpdir,$dir,$outfn,$how,$script) >>
511
512 Helper function for implementing the C<srcdump_process_item> hook.
513 Generates a tarball using cpio and includes it in the prepared source
514 code distribution.
515
516 The arguments are mostly the same as for that hook.  C<$dir> is the
517 root directory at which to start the archive.  C<$how> is a short text
518 string which will be mentioned in the log.
519
520 C<$script> is a shell script fragment which must output a
521 nul-separated list of filenames (e.g. the output of C<find -print0>).
522 It is textually surrounded by C<( )> and will be executed with C<set -e>
523 in force.  Its cwd will be C<$dir>.
524
525 =item C<< $verifier_or_authreq->($data) | CGI::Auth::Flexible-> >>
526
527 Hashes the supplied data using the hash function specified by the
528 C<hash_algorithm> setting, and converts the result to a string of hex
529 digits.
530
531 =back
532
533 =head1 REQUEST TYPES
534
535 The C<$reqtype> values understood by C<check_nonpage> are strings.
536 They are:
537
538 =over
539
540 =item C<PAGE>
541
542 A top-level HTML page load.  May contain confidential information for
543 the benefit of the logged-in user.
544
545 =item C<FRAME>
546
547 An HTML frame.  May contain confidential information for
548 the benefit of the logged-in user.
549
550 =item C<IFRAME>
551
552 An HTML iframe.  May contain confidential information for
553 the benefit of the logged-in user.
554
555 =item C<SRCDUMP>
556
557 Source dump request, whether for the licence or actual source code
558 tarball; returned value is not secret.
559
560 =item C<STYLESHEET>
561
562 CSS stylesheet.  B<MUST NOT> contain any confidential data.  If the
563 stylesheet depends on the user, then attackers may be able to
564 determine what stylesheet the user is using.  Hopefully this is not a
565 problem.
566
567 =item C<FAVICON>
568
569 "Favicon" - icon for display in the browser's url bar etc.  We aren't
570 currently aware of a way that attackers can get a copy of this.
571
572 =item C<ROBOTS>
573
574 C<robots.txt>.  Should not contain any confidential data (obviously).
575
576 =item C<IMAGE>
577
578 Inline image, for an C<< <img src=...> >> element.
579
580 Unfortunately it is not possible to sensibly show top-level
581 confidential images (that is, have the user's browser directly visit a
582 url which resolves to an image rather than an HTML page with an inline
583 image).  This is because images need to have a per-session hidden form
584 parameter to avoid cross-site scripting, which breaks bookmarks etc.
585
586 =item C<SCRIPT>
587
588 JavaScript for a C<< <script> >> element.  (Possibly confidential for
589 the user.)
590
591 =item C<AJAX-XML>
592
593 C<< XMLHttpRequest >> returning XML data.  (Possibly
594 confidential for the user.)
595
596 =item C<AJAX-JSON>
597
598 C<< XMLHttpRequest >> returning JSON data.  (Possibly
599 confidential for the user.)
600
601 =item C<AJAX-OTHER>
602
603 C<< XMLHttpRequest >> returning data of some other kind.  (Possibly
604 confidential for the user.)
605
606 =back.
607
608 =head1 DIVERT SPEC
609
610 The return value from C<check_divert> indicates how the request should
611 be handled.  It is C<undef> if all is well and the user is logged in.
612
613 Otherwise the return value is a hash ref with the following keys:
614
615 =over
616
617 =item C<Kind>
618
619 Scalar string indicating the kind of diversion required.
620
621 =item C<Message>
622
623 Scalar string for display to the user in relation to the diversion.
624 Has already been translated.  In HTML but normally does not contain
625 any tags.
626
627 =item C<CookieSecret>
628
629 The login cookie which should be set along with whatever response is
630 sent to the client.  The value in the hash is the actual value
631 of the cookie as a string.  C<undef> means no cookie setting header
632 should be sent; C<''> means the cookie should be cleared.
633
634 =item C<Params>
635
636 The extra hidden form parameters (and the C<PATH_INFO>) which should
637 be set when the subsequent request bounces back from the client, in
638 the form used by C<url_with_query_params>.
639
640 The contents of this hashref does not include the CAF-specific
641 parameters such as the secret cookie, those which follow from the kind
642 of diversion requested, etc.
643
644 It is correct to always include the contents of C<Params> as hidden
645 parameters in the urls for all redirections, and as hidden input
646 fields in all generated forms.  The specific cases where C<Params> is
647 currently relevant are also mentioned in the text for each divert
648 kind.
649
650 =back
651
652 The values of C<Kind> are:
653
654 =over
655
656 =item C<SRCDUMP->I<item>
657
658 We should respond by sending our application source code.  I<item>
659 (which will contain only word characters, and no lower case) is the
660 specific item to send, normally C<SOURCE> or C<LICENCE>.
661
662 =item C<REDIRECT-HTTPS>
663
664 We should respond with an HTTP redirect to the HTTPS instance of our
665 application.
666
667 =item C<REDIRECT-LOGGEDOUT>
668
669 We should redirect to a page showing that the user has been logged
670 out.  (Ie, to a url with one of the the C<loggedout_param_names> set.)
671
672 =item C<SMALLPAGE-LOGGEDOUT>
673
674 We should generate a page showing that the user has been logged out.
675 There can be a link on the page pointing to the login page so that the
676 user can log back in.
677
678 =item C<SMALLPAGE-NOCOOKIE>
679
680 We should generate a page reporting that the user does not have
681 cookies enabled.  It should probably contain a link pointing to the
682 login page with additionally all the parameters in C<Params>.  When
683 this divert spec is generated, C<Message> will explain the problem
684 with cookies so there is no need to do that again in the page body if
685 you include the contents of C<Message>.
686
687 =item C<LOGIN-STALE>
688
689 The user's session was stale (this is described in C<Message>).  We
690 should generate a login form.
691
692 =item C<LOGIN-BAD>
693
694 The user supplied bad login credentials.  The details are in
695 C<Message>.  We should generate a login form (with additionally the
696 parameters from C<Params> as hidden fields).
697
698 =item C<LOGIN-INCOMINGLINK>
699
700 We should generate a login form (with the specified parameters); the
701 user is entering the site via a cross-site link but is not yet logged
702 in.
703
704 =item C<LOGIN-FRESH>
705
706 We should generate a login form.  The user is not yet logged in.
707
708 =item C<REDIRECT-LOGGEDIN>
709
710 We should redirect to our actual application, with the specified
711 parameters.  (The user has just logged in.)
712
713 =item C<MAINPAGEONLY>
714
715 We should generate our main page but B<ignoring all form parameters>
716 and B<ignoring the path_info>.  Most applications will find this
717 difficult to implement.
718
719 An alternative is to generate a small page with a form or link which
720 submits our own main page without any parameters.
721
722 (Applications which set C<promise_check_mutate> do not see this divert
723 kind.)
724
725 =head1 SETTINGS
726
727 C<new_verifier> and C<new_request> each take a list of settings, as
728 a list of pairs C<< key => value >> (like a Perl hash assignment).
729
730 The settings supplied to C<new_verifier> are stored in the verifier
731 and will apply to all authreqs made from it unless overridden in the
732 call to C<new_request>
733
734 When a setting is described as a hook function, it should be a
735 coderef.  The first argument will be the query object from
736 L<CGI(3perl)> (strictly, it will be whatever value was passed to
737 C<new_request>).  The second argument will be the authreq object (the
738 return value from C<new_request>).
739 Ie, C<< sub some_hook ($$...) { my ($cgi,$authreq,@stuff) = @_ ... >>
740
741 In bullet point headings, the hook functions are shown in the form
742 C<< some_hook($cgi,$authreq,@stuff) >> even though this would not be
743 legal syntax.  This should be read to mean that the
744 %implicit_settings_hash{'some_hook'}($cgi,$authreq,@stuff)
745 would be a legal call.  (However, the settings hash is not exposed.)
746
747 When a hook's default implementation is mentioned and named, that
748 function won't also be described in the section on the module's
749 functions.
750
751 =over
752
753 =head2 GENERAL SETTINGS
754
755 =item C<dir>
756
757 The directory CGI::Auth::Generic should use for its data storage.
758 This is actually just a default absolute path used when the other
759 path settings are relative values.
760
761 Must be an absolute filename.
762
763 =item C<db_dbh>
764
765 CGI::Auth::Flexible needs a database for recording users' login
766 session.  This database needs to be shared across all instances of the
767 web application, so in a multi-node cluster it needs to be your actual
768 database.
769
770 CGI::Auth::Flexible will create the table and index it needs if they
771 don't already exist, and will manage their contents.  You do not need
772 to integrate them into the rest of your webapp's data storage.  (In
773 particular, there is no need for transactional integrity across
774 changes made by CAF and your own application.)
775
776 By default, CAF uses a sqlite3 database stored on local disk in the
777 file named by C<db_path>.  This will be suitable for all
778 applications which run on a single host.
779
780 This value, if supplied, should be a DBI handle for the database.
781
782 =item C<db_dsn>
783
784 This is the DSN to pass to C<< DBI->connect >>.  Used only if
785 C<db_dbh> is not supplied.
786
787 =item C<db_path>
788
789 Path to the sqlite3 database used for CAF's session storage.  The
790 default is C<caf.db>.
791
792 Used only if neither C<db_dbh> or C<db_dsn> are supplied.
793
794 If this is a relative path, it is in C<dir>.
795
796 =item C<db_prefix>
797
798 Prefix for the SQL tables and indices to use (and to create, if
799 necessary).
800
801 See L</DATABASE TABLES>.
802
803 =item C<keys_path>
804
805 Path to the keys file used by CAF.  This arrangement will change in
806 the future.  See L</BUGS>.
807
808 =item C<random_source>
809
810 Special file to read random numbers from.  Should return
811 cryptographically secure (pseudo)-random bytes, unpredictable to
812 adversaries (even ones on the same machine).
813
814 On Linux, there is no device which is properly suitable.  This is a
815 bug in Linux.  You can use C</dev/random> which can block
816 unnecessarily even though the kernel PRNG has been properly seeded and
817 is fine, or C</dev/urandom> which might return values which attackers
818 can predict if the kernel PRNG has not been properly seeded.
819
820 The default is C</dev/urandom>.
821
822 =item C<secretbits>
823
824 Length of the assoc secret.  Defaults to 128.
825
826 =item C<hash_algorithm>
827
828 Must be a string suitable for use with C<new Digest>.
829 Defaults to C<SHA-256>.
830
831 =item C<login_timeout>
832
833 A user will be logged out this many seconds after they first logged
834 in.  Default: 86400 (one day).
835
836 =item C<login_form_timeout>
837
838 A login form becomes invalid this many seconds after it has been sent.
839 Default: 3600 seconds (one hour).
840
841 =item C<key_rollover>
842
843 The key used for generating assoc secrets is rolled over approximately
844 this often (in seconds).  Default: 86400.
845
846 =item C<assoc_param_name>
847
848 Name of the hidden form parameter.  Default: C<caf_assochash>.
849
850 =item C<cookie_name>
851
852 Name of the cookie used for login sessions.  Default:
853 C<caf_assocsecret>.
854
855 =item C<password_param_name>
856
857 Name of the password field in the login form.  Default: C<password>.
858
859 Used by C<login_ok_password> (the default C<login_ok> hook),
860 C<gen_plain_login_form> and the default C<is_login> hook.
861
862 =item C<username_param_names>
863
864 Arrayref of name(s) of username form parameters.
865
866 The first entry is used by C<login_ok_password> (the default
867 C<login_ok> hook) to pass to the C<username_password_error> hook and
868 used as the username if all is well.
869
870 All the entries are used by C<gen_plain_login_fork> (the default
871 C<gen_login_form> hook for C<check_ok>) to generate form entry fields.
872
873 The default is C<['username']>.
874
875 =item C<logout_param_names>
876
877 Arrayref of name(s) of form parameters indicating that the request is
878 a logout request.
879
880 Used by the default C<is_logout> hook.
881
882 If you want users to be able to explicitly log out, you need to
883 provide a logout button, something like
884 C<< <input type="submit" name="caf_logout" ...>>
885
886 The default is C<['caf_logout']>
887
888 =item C<logged_param_names>
889
890 Arrayref of name(s) of form parameters indicating that user has just
891 logged out.  (During the logout process, the actual logout action is a
892 POST request, whose response redirects to the "you have been logged
893 out" page; these form parameters are for this second page.)
894
895 Used by the default C<is_loggedout> hook.
896
897 The first entry is used by C<check_ok> to generate the redirection.
898
899 The default is C<['caf_loggedout']>
900
901 =item C<promise_check_mutate>
902
903 Boolean.  If true, is a declaration by the application that it is
904 mutatin-aware.  See L</MUTATING OPERATIONS AND EXTERNAL LINKS>.
905
906 The default is 0.
907
908 =item C<encrypted_only>
909
910 Boolean.  If true, CAF will insist that all transactions be done over
911 an encrypted http connection.  It will redirect unencrypted requests
912 to the https instance of the applicattion, and will set the encrypted
913 only flag on its cookie.
914
915 The default is 1.
916
917 =back
918
919 =item C<< get_url($cgi,$authreq) >>
920
921 Hook which returns the URL of this web application.  By default, we
922 call C<< $cgi->url() >> for each request, but you can fix this if you
923 prefer.
924
925 =item C<< is_login,is_logout,is_loggedout($cgi,$authreq) >>
926
927 Hook which returns a boolean indicating whether the request was,
928 respectively: a login form submission (ie, username and password); a
929 logout request (submission resulting from the user pressing the
930 "logout" button); "logged out" page (redirection from the logout
931 POST).
932
933 The default is to check whether any of the corresponding request
934 parameters (C<< login_param_names >> etc.) was supplied, using the
935 C<get_param> hook.
936
937 =back
938
939 =head2 SETTINGS (HOOKS) RELATED TO THE CGI REQUEST OBJECT
940
941 =over
942
943 =item C<< get_param($cgi,$authreq,$param) >>
944
945 Returns the value of a single-valued form parameter.
946 The default is to call C<< $cgi->param($param) >>.
947 The semantics are the same as that of C<CGI::param>.
948
949 =item C<< get_params($cgi,$authreq) >>
950
951 Returns a hash of the parameters.  The return value is a hashref whose
952 keys are the parameter names and whose values are arrayrefs, one entry
953 in the arrayref for each value.
954
955 The default is to call C<< $cgi->Vars() >>, expect the
956 results to look like those from C<CGI::Vars>, and massage them into
957 the required form with split.
958
959 =item C<< get_path_info($cgi,$authreq) >>
960
961 Returns the PATH_INFO of the request.  The default is to
962 call C<< $cgi->path_info() >>.
963
964 =item C<< get_cookie($cgi,$authreq) >>
965
966 Returns the value of the CAF cookie sent with the request, or undef if
967 none was supplied.  The default is to call C<<
968 $cgi->cookie($cookie_name) >> (where C<$cookie_name> is from the
969 setting of the same name).  The return value should be the scalar
970 value of the cookie.
971
972 =item C<< get_method($cgi,$authreq) >>
973
974 Returns the HTTP method as a string.  The default is to call
975 C<< $cgi->request_method() >>.
976
977 =back
978
979 =item C<< is_https($cgi,$authreq) >>
980
981 Returns a boolean indicating whether the request was over an encrypted
982 channel.  The default is C<< !!$cgi->https() >>.  See C<encrypted_only>.
983
984 =back
985
986 =head2 SETTINGS RELATED TO HTML GENERATION
987
988 These are only used if you call C<check_ok> (or other functions
989 mentioned in this section).
990
991 Settings whose names are of the form C<gen_...> are hooks which each
992 return an array of strings, normally HTML strings, for use by
993 C<check_ok> (or, in turn, other hooks, or your application).  These
994 are often documented simply by showing the output produced.  In many
995 cases parts of the output are in turn obtained from other hooks.  In
996 some cases the default implementations have been given names for
997 convenient use by your application.  They will be called in array
998 context.
999
1000 We'll write C<gettext(something)> even though actually there is a hook
1001 to control the translation function used.
1002
1003 =over
1004
1005 =item C<handle_divert>($cgi,$authreq,$divert))
1006
1007 C<check_ok> calls this hook before producing output of its own.  If
1008 you want to handle some but not all diversions yourself, you may set
1009 this hook.  The hook should either do nothing and return false, or
1010 return true if it has handled the request (or arrange for the request
1011 to be handled).  If the hook returns true then C<check_ok> simply
1012 returns 0.
1013
1014 =item C<gen_login_form>($cgi,$authreq,$divert))
1015
1016 Default: a table (used mostly for layout) containing input fields for
1017 a login form.  Must be within a C<< <form> >> element, but doesn't
1018 generate it.  Has text fields for every entry in
1019 C<username_param_names> (in each case associated with a description
1020 C<< gettext(ucfirst $parameter_name) >>, a password field (with
1021 description C<gettext("Password")>, and a login submit button (with
1022 description C<gettext("Login")>.
1023
1024 Default is available as the module function C<gen_plain_login_form>.
1025
1026 =item C<gen_login_link>($cgi,$authreq))
1027
1028 Default:
1029
1030  <a href="http:...">gettext(Log in again to continue.)</a>
1031
1032 Default is available as the module function C<gen_plain_login_link>.
1033
1034 =item C<gen_postmainpage_form>($cgi,$authreq,$params))
1035
1036 Default: form contents (but not the C<< <form> >> element):
1037
1038 C<$params> (in the form returned by the C<get_params> hook) as hidden
1039 fields, and also:
1040
1041  <input type="submit" ... value=getext('Continue')>
1042
1043 Default is available as the module function C<gen_postmainpage_form>.
1044
1045 =item C<gen_start_html>($cgi,$authreq,$title)
1046
1047 Default: C<$cgi->start_html($title)>
1048
1049 =item C<gen_end_html>($cgi,$authreq,$title)
1050
1051 Default: C<$cgi->end_html($title)>
1052
1053 =item C<gen_footer_html>($cgi,$authreq)>
1054
1055 Default:
1056
1057  <hr><address>
1058  Powered by Free / Libre / Open Source Software
1059  according to the [gen_licence_link_html].
1060  [gen_source_link_html].
1061  </address>
1062
1063 Default is available as the module function C<gen_plain_footer_html>.
1064
1065 =item C<gen_licence_link_html>($cgi,$authreq)>
1066
1067 Default: uses C<url_with_query_params> to generate a URL for
1068 downloading the licence, and returns:
1069   <a href="...">GNU Affero GPL</a>
1070
1071 Default is available as the module function C<gen_plain_licence_link_html>.
1072
1073 =item C<gen_source_link_html>($cgi,$authreq)>
1074
1075 Default: uses C<url_with_query_params> to generate a URL for
1076 downloading the source, and returns:
1077   <a href="...">Source available</a>
1078
1079 Default is available as the module function C<gen_plain_source_link_html>.
1080
1081 =item C<form_entry_size>
1082
1083 Size of generated text entry fields.  Default is 60.
1084
1085 =item C<dummy_param_name_prefix>
1086
1087 Some of CAF's HTML-generating functions need to invent form parameter
1088 names.  They will all start with this string.  Default: C<caf__>.
1089
1090 =head2 SETTINGS FOR SOURCE CODE DOWNLOAD FACILITY
1091
1092 =over
1093
1094 =item C<srcdump_param_name>
1095
1096 Form parameter name used to indicate that this is a source download
1097 request.  If this parameter is supplied, C<check_ok> and
1098 C<check_divert> will arrange for the applicaton source code to be
1099 delivered as the response (in C<check_ok>'s case by doing it itself
1100 and in C<check_divert>'s case by asking your application to do so.
1101
1102 Default is C<caf_srcdump>.
1103
1104 =item C<srcdump_path>
1105
1106 Path to the directory used for storing pre-prepared source downloads.
1107 Defaults to C<caf-srcdump>.
1108
1109 If this is a relative path, it is in C<dir>.
1110
1111 =item C<srcdump_dump($cgi,$authreq,$srcobj)>
1112
1113 Dump the source code (C<$srcobj='source'> or licence data
1114 (C<$srcobj='licence'>).  The default implementation checks that
1115 C<$srcobj> has reasonable syntax and uses the files C<$srcobj.data>
1116 and C<$srcobj.ctype> with the C<dump> hook.
1117
1118 =item C<dump($cgi,$authreq,$contenttype,$datafilehandle)>
1119
1120 Responds to the request by sending the contents of $datafilehandle
1121 (which should just have been opened) and specifying a content type of
1122 $contenttype.
1123
1124 The default implmentation uses the C<print> hook, and also calls
1125 C<$cgi->header('-type' => $contenttype>, and is available as the
1126 module function C<dump_plain>.
1127
1128 =item C<srcdump_prepare($cgi,$verifier)>
1129
1130 Prepares the source code for download when requested.  Invoked by
1131 C<new_verifier>, always, immediately before it returns the
1132 just-created verifier object.
1133
1134 The default implementation is the module function
1135 C<srcdump_dirscan_prepare>, which prepares a manifest, licence file
1136 and source code tarball of tarballs, as follows:
1137
1138 It processes each entry in the return value from C<srcdump_listitems>.
1139 These are the software's include directories and any other directories
1140 containing source code.  It handles C<.> specially (see
1141 C<srcdump_filter_cwd>).
1142
1143 For each entry it looks, relative to that, for the licence as a file
1144 with a name mentioned in C<srcdump_licence_files>.  The first such
1145 file found is considered to be the licence.  It then calls the hook
1146 C<srcdump_process_item> for the entry.
1147
1148 The licence, a manifest file, and all the outputs generated by the
1149 calls to C<srcdump_process_item>, are tarred up and compressed as a
1150 single source tarball.
1151
1152 It uses the directory named by C<srcdump_path> as its directory for
1153 working and output files.  It uses the filename patterns
1154 C<generate.*>, C<licence.*>, C<s.[a-z][a-z][a-z].*>, C<manifest.*>,
1155 C<source.*> in that directory.
1156
1157 =item C<srcdump_process_item>($cgi,$verifier,$dumpdir,$item,\&outfn,\$needlicence,\%dirsdone)>
1158
1159 Processes a single include directory or software entry, so as to
1160 include the source code found there.  Called only by the default
1161 implementation of C<srcdump_prepare>.
1162
1163 C<$dumpdir> is the directory for working and output files.  C<$item>
1164 is the real (no symlinks) absolute path to the item.
1165
1166 C<\$needlicence> is a ref to a scalar: this scalar is undef if we have
1167 already found the licence file; otherwise it is the filename to which
1168 the licence should be copied.  If the referent is undef on entry,
1169 C<srcdump_process_item> needs to see if it finds the licence; if it
1170 does it should copy it to the named file and then set the scalar to
1171 undef.
1172
1173 C<\%dirsdone> is a ref to the hash used by C<srcdump_prepare> to avoid
1174 including a single directory more than once.  If
1175 C<srcdump_process_item> decides to process a directory other than
1176 C<$item> it should check this hash with the real absolute path of the
1177 other directoy as a key: if the hash entry is true, it has already
1178 been done and should be skipped; otherwise the hash entry should be set.
1179
1180 C<\&outfn> is a coderef which C<srcdump_process_item> should call each
1181 time it wants to generate a file which should be included as part of
1182 the source code.  It should be called using one of these patterns:
1183    $outfn->("message for manifest");
1184    $outfile = $outfn->("message for manifest", "extension");
1185 The former simply prints the message into the manifest in the form
1186   none: message for manifest
1187 The latter generates and returns a filename which should then
1188 be created and filled with some appropriate data.  C<"extension">
1189 should be a string for the file extension, eg C<"txt">.  The output
1190 can be written directly to the named file: there is no need to
1191 write to a temporary file and rename.  C<$outfn> writes the filename
1192 and the message to the manifest, in the form
1193   filename leaf: message
1194 In neither case is the actual name of C<$dir> on the system
1195 disclosed per se although of course some of the contents of some of
1196 the files in the source code dump may mention it.
1197
1198 The default implementation is the module function
1199 C<srcdump_process_item>.
1200
1201 It skips directories for which C<srcdump_system_dir> returns true.
1202
1203 It then searches the item and its parent
1204 directories for a vcs metadata directory (one of the names in
1205 C<srcdump_vcs_dirs>); if found, it calls the C<srcdump_byvcs> hook
1206 (after checking and updaeing C<%dirsdone>).
1207 Otherwise it calls the C<srcdump_novcs> hook.
1208
1209 =item C<srcdump_novcs($cgi,$verifier,$dumpdir,$item,$outfn)>
1210
1211 Called by the default implementation of C<srcdump_process_item>, with
1212 the same arguments, if it doesn't find vcs metadata.
1213
1214 The default implementation is the module function C<srcdump_novcs>.
1215
1216 If C<$item> is a directory, it uses C<srcdump_dir_cpio> to prepare a
1217 tarball of all the files under C<$item> which have the world read bit
1218 set.  Directories are not included (and their permissions are
1219 disregarded).  The contents of C<srcdump_excludes> are excluded.
1220
1221 If it's a plain file it uses C<srcdump_file> to include the file.
1222
1223 =item C<srcdump_byvcs($cgi,$verifier,$dumpdir,$item,$outfn,$vcs)>
1224
1225 Called by the default implementation of C<srcdump_process_item>, with
1226 the same arguments, if it finds vcs metadata.  The additional argument
1227 C<$vcs> is derived from the entry of C<srcump_vcs_dirs> which was
1228 used: it's the first sequence of word characters, lowercased.
1229
1230 The default implementation is the module function C<srcdump_byvcs>.
1231 It simply calls C<srcdump_dir_cpio> with a script from the setting
1232 C<srcdump_vcsscript>.
1233
1234 =item C<srcdump_vcs_dirs>
1235
1236 Array ref of leaf names of vcs metadata directories.  Used by the
1237 default implementation of C<srcdump_process_item>.  The default value
1238 is C<['.git','.hg','.bzr','.svn']>.
1239
1240 =item C<srcdump_vcs_script>
1241
1242 Hash ref of scripts for generating vcs metadata.  Used by the default
1243 implementation of C<srcdump_byvcs>.  The keys are values of C<$vcs>
1244 (see C<srcdump_byvcs>); the values are scripts as for
1245 C<srcdump_dir_cpio>.
1246
1247 The default has an entry only for C<git>:
1248   git ls-files -z
1249   git ls-files -z --others --exclude-from=.gitignore
1250   find .git -print0
1251
1252 =item C<srcdump_excludes>
1253
1254 Array ref of exclude glob patterns, used by the default implementation
1255 of C<srcdump_novcs>.  The default value is C<['*~','*.bak','*.tmp','#*#']>.
1256
1257 Entries must not contain C<'> or C<\>.
1258
1259 =item C<srcdump_listitems($cgi,$verifier)>
1260
1261 Returns an array of directories which might contain source code of the
1262 web application and which should be therefore be considered for
1263 including in the source code delivery.
1264
1265 Used by the default implementation of C<srcdump_prepare>.
1266
1267 Entries must be directories, plain files, or nonexistent; they may
1268 also be symlinks which resolve to one of those.
1269
1270 If C<.> is included it may be treated specially - see
1271 C<srcdump_filter_cwd>.
1272
1273 The default implementation returns 
1274 C<(@INC, $ENV{'SCRIPT_FILENAME'}, $0)>.
1275
1276 =item C<srcdump_system_dir($cgi,$verifier,$dir)>
1277
1278 Determines whether C<$dir> is a "system directory", in which any
1279 source code used by the application should nevertheless not be
1280 included in the source code dump.
1281
1282 Used by the default implementation of C<srcdump_item>.
1283
1284 The default implementation is as follows: Things in C</etc/> are
1285 system directories.  Things in C</usr/> are too, unless they are in
1286 C</usr/local/> or C</usr/lib/cgi*>.
1287
1288 =item C<srcdump_filter_cwd>
1289
1290 Boolean which controls the handling of C<.> if it appears in the
1291 return value from C<srcdump_listitems>.  Used only by the default
1292 implementation of C<srcdump_prepare>.
1293
1294 If set to false, C<.> is treated normally and no special action is
1295 taken.
1296
1297 However often the current directory may be C</>, or a data directory,
1298 or some other directory containing data which is confidential, or
1299 should not be included in the public source code distribution for
1300 other reasons.  And for historical reasons Perl has C<@INC> containing
1301 C<.> by default (which is arguably dangerous and wrong).
1302
1303 So the default this setting is true, which has the following effects:
1304
1305 C<.> is not searched for source code even if it appears in C<@INC>.
1306 C<.> is removed from C<@INC> and C<%INC> is checked to see if any
1307 modules appear to have already been loaded by virtue of C<.> appearing
1308 in C<@INC> and if they have it is treated as a fatal error.
1309
1310 Only the literal string C<.> is affected.  If the cwd is included by
1311 any other name it is not treated specially regardless of this setting.
1312
1313 =back
1314
1315 =head1 DATABASE TABLES
1316
1317 In a simple application, you do not need to worry about this.  But if
1318 your application runs on multiple frontend hosts with a shared
1319 database, you may need to create for yourself the tables and indices
1320 used by CGI::Auth::Flexible.
1321
1322 By default, every time CAF starts up, it attempts to execute certain
1323 fixed database statements to create the tables and indices it needs.
1324 These are run with C<$dbh->{PrintError}> set to 0.  The effect with
1325 sqlite (the default database) is that the tables and indices are
1326 created iff they do not already exist, and that no spurious errors are
1327 reported anywhere.
1328
1329 If you use a different database, or just prefer to do things
1330 differently, you can set up the tables yourself and/or disable or
1331 modify the default setup statements, via the C<db_setup_stmts>
1332 setting.
1333
1334 The tables needed are:
1335
1336
1337 xxx document _db_setup_do
1338 xxx make _db_setup_do explicitly overrideable
1339
1340
1341 xxx remaining settings
1342  db_password
1343  username_password_error
1344  login_ok
1345  get_cookie_domain
1346  gettext
1347  print
1348  debug
1349
1350 xxx document cookie usage
1351 xxx document construct_cookie fn
1352
1353 xxx document @default_db_setup_statements
1354
1355 xxx bugs wrong default random on Linux
1356 xxx bugs wrong default random on *BSD
1357 xxx bugs keys not shared should be in db
1358 xxx rename caf_assocsecret default cookie name
1359 xxx mention relationship between login_timeout and cookies