* auth-source.el (auth-sources): Search ~/.netrc as well by default.
[gnus] / lisp / auth-source.el
1 ;;; auth-source.el --- authentication sources for Gnus and Emacs
2
3 ;; Copyright (C) 2008-2011 Free Software Foundation, Inc.
4
5 ;; Author: Ted Zlatanov <tzz@lifelogs.com>
6 ;; Keywords: news
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
25 ;; This is the auth-source.el package.  It lets users tell Gnus how to
26 ;; authenticate in a single place.  Simplicity is the goal.  Instead
27 ;; of providing 5000 options, we'll stick to simple, easy to
28 ;; understand options.
29
30 ;; See the auth.info Info documentation for details.
31
32 ;; TODO:
33
34 ;; - never decode the backend file unless it's necessary
35 ;; - a more generic way to match backends and search backend contents
36 ;; - absorb netrc.el and simplify it
37 ;; - protect passwords better
38 ;; - allow creating and changing netrc lines (not files) e.g. change a password
39
40 ;;; Code:
41
42 (require 'password-cache)
43 (require 'mm-util)
44 (require 'gnus-util)
45 (require 'netrc)
46 (require 'assoc)
47 (eval-when-compile (require 'cl))
48 (eval-and-compile
49   (or (ignore-errors (require 'eieio))
50       ;; gnus-fallback-lib/ from gnus/lisp/gnus-fallback-lib
51       (ignore-errors
52         (let ((load-path (cons (expand-file-name
53                                 "gnus-fallback-lib/eieio"
54                                 (file-name-directory (locate-library "gnus")))
55                                load-path)))
56           (require 'eieio)))
57       (error
58        "eieio not found in `load-path' or gnus-fallback-lib/ directory.")))
59
60 (autoload 'secrets-create-item "secrets")
61 (autoload 'secrets-delete-item "secrets")
62 (autoload 'secrets-get-alias "secrets")
63 (autoload 'secrets-get-attributes "secrets")
64 (autoload 'secrets-get-secret "secrets")
65 (autoload 'secrets-list-collections "secrets")
66 (autoload 'secrets-search-items "secrets")
67
68 (defvar secrets-enabled)
69
70 (defgroup auth-source nil
71   "Authentication sources."
72   :version "23.1" ;; No Gnus
73   :group 'gnus)
74
75 ;;;###autoload
76 (defcustom auth-source-cache-expiry 7200
77   "How many seconds passwords are cached, or nil to disable
78 expiring.  Overrides `password-cache-expiry' through a
79 let-binding."
80   :group 'auth-source
81   :type '(choice (const :tag "Never" nil)
82                  (const :tag "All Day" 86400)
83                  (const :tag "2 Hours" 7200)
84                  (const :tag "30 Minutes" 1800)
85                  (integer :tag "Seconds")))
86
87 (defclass auth-source-backend ()
88   ((type :initarg :type
89          :initform 'netrc
90          :type symbol
91          :custom symbol
92          :documentation "The backend type.")
93    (source :initarg :source
94            :type string
95            :custom string
96            :documentation "The backend source.")
97    (host :initarg :host
98          :initform t
99          :type t
100          :custom string
101          :documentation "The backend host.")
102    (user :initarg :user
103          :initform t
104          :type t
105          :custom string
106          :documentation "The backend user.")
107    (port :initarg :port
108          :initform t
109          :type t
110          :custom string
111          :documentation "The backend protocol.")
112    (create-function :initarg :create-function
113                     :initform ignore
114                     :type function
115                     :custom function
116                     :documentation "The create function.")
117    (search-function :initarg :search-function
118                     :initform ignore
119                     :type function
120                     :custom function
121                     :documentation "The search function.")))
122
123 (defcustom auth-source-protocols '((imap "imap" "imaps" "143" "993")
124                                    (pop3 "pop3" "pop" "pop3s" "110" "995")
125                                    (ssh  "ssh" "22")
126                                    (sftp "sftp" "115")
127                                    (smtp "smtp" "25"))
128   "List of authentication protocols and their names"
129
130   :group 'auth-source
131   :version "23.2" ;; No Gnus
132   :type '(repeat :tag "Authentication Protocols"
133                  (cons :tag "Protocol Entry"
134                        (symbol :tag "Protocol")
135                        (repeat :tag "Names"
136                                (string :tag "Name")))))
137
138 ;;; generate all the protocols in a format Customize can use
139 ;;; TODO: generate on the fly from auth-source-protocols
140 (defconst auth-source-protocols-customize
141   (mapcar (lambda (a)
142             (let ((p (car-safe a)))
143               (list 'const
144                     :tag (upcase (symbol-name p))
145                     p)))
146           auth-source-protocols))
147
148 (defvar auth-source-creation-defaults nil
149   "Defaults for creating token values.  Usually let-bound.")
150
151 (make-obsolete 'auth-source-hide-passwords nil "Emacs 24.1")
152
153 (defvar auth-source-magic "auth-source-magic ")
154
155 (defcustom auth-source-do-cache t
156   "Whether auth-source should cache information with `password-cache'."
157   :group 'auth-source
158   :version "23.2" ;; No Gnus
159   :type `boolean)
160
161 (defcustom auth-source-debug nil
162   "Whether auth-source should log debug messages.
163
164 If the value is nil, debug messages are not logged.
165
166 If the value is t, debug messages are logged with `message'.  In
167 that case, your authentication data will be in the clear (except
168 for passwords).
169
170 If the value is a function, debug messages are logged by calling
171  that function using the same arguments as `message'."
172   :group 'auth-source
173   :version "23.2" ;; No Gnus
174   :type `(choice
175           :tag "auth-source debugging mode"
176           (const :tag "Log using `message' to the *Messages* buffer" t)
177           (function :tag "Function that takes arguments like `message'")
178           (const :tag "Don't log anything" nil)))
179
180 (defcustom auth-sources '("~/.authinfo.gpg" "~/.authinfo" "~/.netrc")
181   "List of authentication sources.
182
183 The default will get login and password information from
184 \"~/.authinfo.gpg\", which you should set up with the EPA/EPG
185 packages to be encrypted.  If that file doesn't exist, it will
186 try the unencrypted version \"~/.authinfo\" and the famous
187 \"~/.netrc\" file.
188
189 See the auth.info manual for details.
190
191 Each entry is the authentication type with optional properties.
192
193 It's best to customize this with `M-x customize-variable' because the choices
194 can get pretty complex."
195   :group 'auth-source
196   :version "24.1" ;; No Gnus
197   :type `(repeat :tag "Authentication Sources"
198                  (choice
199                   (string :tag "Just a file")
200                   (const :tag "Default Secrets API Collection" 'default)
201                   (const :tag "Login Secrets API Collection" "secrets:Login")
202                   (const :tag "Temp Secrets API Collection" "secrets:session")
203                   (list :tag "Source definition"
204                         (const :format "" :value :source)
205                         (choice :tag "Authentication backend choice"
206                                 (string :tag "Authentication Source (file)")
207                                 (list
208                                  :tag "Secret Service API/KWallet/GNOME Keyring"
209                                  (const :format "" :value :secrets)
210                                  (choice :tag "Collection to use"
211                                          (string :tag "Collection name")
212                                          (const :tag "Default" 'default)
213                                          (const :tag "Login" "Login")
214                                          (const
215                                           :tag "Temporary" "session"))))
216                         (repeat :tag "Extra Parameters" :inline t
217                                 (choice :tag "Extra parameter"
218                                         (list
219                                          :tag "Host"
220                                          (const :format "" :value :host)
221                                          (choice :tag "Host (machine) choice"
222                                                  (const :tag "Any" t)
223                                                  (regexp
224                                                   :tag "Regular expression")))
225                                         (list
226                                          :tag "Protocol"
227                                          (const :format "" :value :port)
228                                          (choice
229                                           :tag "Protocol"
230                                           (const :tag "Any" t)
231                                           ,@auth-source-protocols-customize))
232                                         (list :tag "User" :inline t
233                                               (const :format "" :value :user)
234                                               (choice :tag "Personality/Username"
235                                                       (const :tag "Any" t)
236                                                       (string :tag "Name")))))))))
237
238 (defcustom auth-source-gpg-encrypt-to t
239   "List of recipient keys that `authinfo.gpg' encrypted to.
240 If the value is not a list, symmetric encryption will be used."
241   :group 'auth-source
242   :version "24.1" ;; No Gnus
243   :type '(choice (const :tag "Symmetric encryption" t)
244                  (repeat :tag "Recipient public keys"
245                          (string :tag "Recipient public key"))))
246
247 ;; temp for debugging
248 ;; (unintern 'auth-source-protocols)
249 ;; (unintern 'auth-sources)
250 ;; (customize-variable 'auth-sources)
251 ;; (setq auth-sources nil)
252 ;; (format "%S" auth-sources)
253 ;; (customize-variable 'auth-source-protocols)
254 ;; (setq auth-source-protocols nil)
255 ;; (format "%S" auth-source-protocols)
256 ;; (auth-source-pick nil :host "a" :port 'imap)
257 ;; (auth-source-user-or-password "login" "imap.myhost.com" 'imap)
258 ;; (auth-source-user-or-password "password" "imap.myhost.com" 'imap)
259 ;; (auth-source-user-or-password-imap "login" "imap.myhost.com")
260 ;; (auth-source-user-or-password-imap "password" "imap.myhost.com")
261 ;; (auth-source-protocol-defaults 'imap)
262
263 ;; (let ((auth-source-debug 'debug)) (auth-source-do-debug "hello"))
264 ;; (let ((auth-source-debug t)) (auth-source-do-debug "hello"))
265 ;; (let ((auth-source-debug nil)) (auth-source-do-debug "hello"))
266 (defun auth-source-do-debug (&rest msg)
267   (when auth-source-debug
268     (apply 'auth-source-do-warn msg)))
269
270 (defun auth-source-do-warn (&rest msg)
271   (apply
272     ;; set logger to either the function in auth-source-debug or 'message
273     ;; note that it will be 'message if auth-source-debug is nil
274    (if (functionp auth-source-debug)
275        auth-source-debug
276      'message)
277    msg))
278
279
280 ;; (auth-source-pick nil :host "any" :port 'imap :user "joe")
281 ;; (auth-source-pick t :host "any" :port 'imap :user "joe")
282 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
283 ;;                   (:source (:secrets "session") :host t :port t :user "joe")
284 ;;                   (:source (:secrets "Login") :host t :port t)
285 ;;                   (:source "~/.authinfo.gpg" :host t :port t)))
286
287 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
288 ;;                   (:source (:secrets "session") :host t :port t :user "joe")
289 ;;                   (:source (:secrets "Login") :host t :port t)
290 ;;                   ))
291
292 ;; (setq auth-sources '((:source "~/.authinfo.gpg" :host t :port t)))
293
294 ;; (auth-source-backend-parse "myfile.gpg")
295 ;; (auth-source-backend-parse 'default)
296 ;; (auth-source-backend-parse "secrets:Login")
297
298 (defun auth-source-backend-parse (entry)
299   "Creates an auth-source-backend from an ENTRY in `auth-sources'."
300   (auth-source-backend-parse-parameters
301    entry
302    (cond
303     ;; take 'default and recurse to get it as a Secrets API default collection
304     ;; matching any user, host, and protocol
305     ((eq entry 'default)
306      (auth-source-backend-parse '(:source (:secrets default))))
307     ;; take secrets:XYZ and recurse to get it as Secrets API collection "XYZ"
308     ;; matching any user, host, and protocol
309     ((and (stringp entry) (string-match "^secrets:\\(.+\\)" entry))
310      (auth-source-backend-parse `(:source (:secrets ,(match-string 1 entry)))))
311     ;; take just a file name and recurse to get it as a netrc file
312     ;; matching any user, host, and protocol
313     ((stringp entry)
314      (auth-source-backend-parse `(:source ,entry)))
315
316     ;; a file name with parameters
317     ((stringp (plist-get entry :source))
318      (auth-source-backend
319       (plist-get entry :source)
320       :source (plist-get entry :source)
321       :type 'netrc
322       :search-function 'auth-source-netrc-search
323       :create-function 'auth-source-netrc-create))
324
325     ;; the Secrets API.  We require the package, in order to have a
326     ;; defined value for `secrets-enabled'.
327     ((and
328       (not (null (plist-get entry :source))) ; the source must not be nil
329       (listp (plist-get entry :source))      ; and it must be a list
330       (require 'secrets nil t)               ; and we must load the Secrets API
331       secrets-enabled)                       ; and that API must be enabled
332
333      ;; the source is either the :secrets key in ENTRY or
334      ;; if that's missing or nil, it's "session"
335      (let ((source (or (plist-get (plist-get entry :source) :secrets)
336                        "session")))
337
338        ;; if the source is a symbol, we look for the alias named so,
339        ;; and if that alias is missing, we use "Login"
340        (when (symbolp source)
341          (setq source (or (secrets-get-alias (symbol-name source))
342                           "Login")))
343
344        (if (featurep 'secrets)
345            (auth-source-backend
346             (format "Secrets API (%s)" source)
347             :source source
348             :type 'secrets
349             :search-function 'auth-source-secrets-search
350             :create-function 'auth-source-secrets-create)
351          (auth-source-do-warn
352           "auth-source-backend-parse: no Secrets API, ignoring spec: %S" entry)
353          (auth-source-backend
354           (format "Ignored Secrets API (%s)" source)
355           :source ""
356           :type 'ignore))))
357
358     ;; none of them
359     (t
360      (auth-source-do-warn
361       "auth-source-backend-parse: invalid backend spec: %S" entry)
362      (auth-source-backend
363       "Empty"
364       :source ""
365       :type 'ignore)))))
366
367 (defun auth-source-backend-parse-parameters (entry backend)
368   "Fills in the extra auth-source-backend parameters of ENTRY.
369 Using the plist ENTRY, get the :host, :port, and :user search
370 parameters."
371   (let ((entry (if (stringp entry)
372                    nil
373                  entry))
374         val)
375     (when (setq val (plist-get entry :host))
376       (oset backend host val))
377     (when (setq val (plist-get entry :user))
378       (oset backend user val))
379     (when (setq val (plist-get entry :port))
380       (oset backend port val)))
381   backend)
382
383 ;; (mapcar 'auth-source-backend-parse auth-sources)
384
385 (defun* auth-source-search (&rest spec
386                                   &key type max host user port secret
387                                   create delete
388                                   &allow-other-keys)
389   "Search or modify authentication backends according to SPEC.
390
391 This function parses `auth-sources' for matches of the SPEC
392 plist.  It can optionally create or update an authentication
393 token if requested.  A token is just a standard Emacs property
394 list with a :secret property that can be a function; all the
395 other properties will always hold scalar values.
396
397 Typically the :secret property, if present, contains a password.
398
399 Common search keys are :max, :host, :port, and :user.  In
400 addition, :create specifies how tokens will be or created.
401 Finally, :type can specify which backend types you want to check.
402
403 A string value is always matched literally.  A symbol is matched
404 as its string value, literally.  All the SPEC values can be
405 single values (symbol or string) or lists thereof (in which case
406 any of the search terms matches).
407
408 :create t means to create a token if possible.
409
410 A new token will be created if no matching tokens were found.
411 The new token will have only the keys the backend requires.  For
412 the netrc backend, for instance, that's the user, host, and
413 port keys.
414
415 Here's an example:
416
417 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
418                                         (A    . \"default A\"))))
419   (auth-source-search :host \"mine\" :type 'netrc :max 1
420                       :P \"pppp\" :Q \"qqqq\"
421                       :create t))
422
423 which says:
424
425 \"Search for any entry matching host 'mine' in backends of type
426  'netrc', maximum one result.
427
428  Create a new entry if you found none.  The netrc backend will
429  automatically require host, user, and port.  The host will be
430  'mine'.  We prompt for the user with default 'defaultUser' and
431  for the port without a default.  We will not prompt for A, Q,
432  or P.  The resulting token will only have keys user, host, and
433  port.\"
434
435 :create '(A B C) also means to create a token if possible.
436
437 The behavior is like :create t but if the list contains any
438 parameter, that parameter will be required in the resulting
439 token.  The value for that parameter will be obtained from the
440 search parameters or from user input.  If any queries are needed,
441 the alist `auth-source-creation-defaults' will be checked for the
442 default prompt.
443
444 Here's an example:
445
446 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
447                                         (A    . \"default A\"))))
448   (auth-source-search :host '(\"nonesuch\" \"twosuch\") :type 'netrc :max 1
449                       :P \"pppp\" :Q \"qqqq\"
450                       :create '(A B Q)))
451
452 which says:
453
454 \"Search for any entry matching host 'nonesuch'
455  or 'twosuch' in backends of type 'netrc', maximum one result.
456
457  Create a new entry if you found none.  The netrc backend will
458  automatically require host, user, and port.  The host will be
459  'nonesuch' and Q will be 'qqqq'.  We prompt for A with default
460  'default A', for B and port with default nil, and for the
461  user with default 'defaultUser'.  We will not prompt for Q.  The
462  resulting token will have keys user, host, port, A, B, and Q.
463  It will not have P with any value, even though P is used in the
464  search to find only entries that have P set to 'pppp'.\"
465
466 When multiple values are specified in the search parameter, the
467 user is prompted for which one.  So :host (X Y Z) would ask the
468 user to choose between X, Y, and Z.
469
470 This creation can fail if the search was not specific enough to
471 create a new token (it's up to the backend to decide that).  You
472 should `catch' the backend-specific error as usual.  Some
473 backends (netrc, at least) will prompt the user rather than throw
474 an error.
475
476 :delete t means to delete any found entries.  nil by default.
477 Use `auth-source-delete' in ELisp code instead of calling
478 `auth-source-search' directly with this parameter.
479
480 :type (X Y Z) will check only those backend types.  'netrc and
481 'secrets are the only ones supported right now.
482
483 :max N means to try to return at most N items (defaults to 1).
484 When 0 the function will return just t or nil to indicate if any
485 matches were found.  More than N items may be returned, depending
486 on the search and the backend.
487
488 :host (X Y Z) means to match only hosts X, Y, or Z according to
489 the match rules above.  Defaults to t.
490
491 :user (X Y Z) means to match only users X, Y, or Z according to
492 the match rules above.  Defaults to t.
493
494 :port (P Q R) means to match only protocols P, Q, or R.
495 Defaults to t.
496
497 :K (V1 V2 V3) for any other key K will match values V1, V2, or
498 V3 (note the match rules above).
499
500 The return value is a list with at most :max tokens.  Each token
501 is a plist with keys :backend :host :port :user, plus any other
502 keys provided by the backend (notably :secret).  But note the
503 exception for :max 0, which see above.
504
505 The token's :secret key can hold a function.  In that case you
506 must call it to obtain the actual value."
507   (let* ((backends (mapcar 'auth-source-backend-parse auth-sources))
508          (max (or max 1))
509          (ignored-keys '(:create :delete :max))
510          (keys (loop for i below (length spec) by 2
511                      unless (memq (nth i spec) ignored-keys)
512                      collect (nth i spec)))
513          (found (auth-source-recall spec))
514          filtered-backends accessor-key found-here goal matches backend)
515
516     (if (and found auth-source-do-cache)
517         (auth-source-do-debug
518          "auth-source-search: found %d CACHED results matching %S"
519          (length found) spec)
520
521       (assert
522        (or (eq t create) (listp create)) t
523        "Invalid auth-source :create parameter (must be nil, t, or a list): %s %s")
524
525       (setq filtered-backends (copy-sequence backends))
526       (dolist (backend backends)
527         (dolist (key keys)
528           ;; ignore invalid slots
529           (condition-case signal
530               (unless (eval `(auth-source-search-collection
531                               (plist-get spec key)
532                               (oref backend ,key)))
533                 (setq filtered-backends (delq backend filtered-backends))
534                 (return))
535             (invalid-slot-name))))
536
537       (auth-source-do-debug
538        "auth-source-search: found %d backends matching %S"
539        (length filtered-backends) spec)
540
541       ;; (debug spec "filtered" filtered-backends)
542       (setq goal max)
543       ;; First go through all the backends without :create, so we can
544       ;; query them all.
545       (let ((uspec (copy-sequence spec)))
546         (plist-put uspec :create nil)
547         (dolist (backend filtered-backends)
548           (let ((match (apply
549                         (slot-value backend 'search-function)
550                         :backend backend
551                         uspec)))
552             (when match
553               (push (list backend match) matches)))))
554       ;; If we didn't find anything, then we allow the backend(s) to
555       ;; create the entries.
556       (when (and create
557                  (not matches))
558         (dolist (backend filtered-backends)
559           (unless matches
560             (let ((match (apply
561                           (slot-value backend 'search-function)
562                           :backend backend
563                           :create create
564                           :delete delete
565                           spec)))
566               (when match
567                 (push (list backend match) matches))))))
568
569       (setq backend (caar matches)
570             found-here (cadar matches))
571
572       (block nil
573         ;; if max is 0, as soon as we find something, return it
574         (when (and (zerop max) (> 0 (length found-here)))
575           (return t))
576
577         ;; decrement the goal by the number of new results
578         (decf goal (length found-here))
579         ;; and append the new results to the full list
580         (setq found (append found found-here))
581
582         (auth-source-do-debug
583          "auth-source-search: found %d results (max %d/%d) in %S matching %S"
584          (length found-here) max goal backend spec)
585
586         ;; return full list if the goal is 0 or negative
587         (when (zerop (max 0 goal))
588           (return found))
589
590         ;; change the :max parameter in the spec to the goal
591         (setq spec (plist-put spec :max goal))
592
593         (when (and found auth-source-do-cache)
594           (auth-source-remember spec found))))
595
596     found))
597
598 ;;; (auth-source-search :max 1)
599 ;;; (funcall (plist-get (nth 0 (auth-source-search :max 1)) :secret))
600 ;;; (auth-source-search :host "nonesuch" :type 'netrc :K 1)
601 ;;; (auth-source-search :host "nonesuch" :type 'secrets)
602
603 (defun* auth-source-delete (&rest spec
604                                   &key delete
605                                   &allow-other-keys)
606   "Delete entries from the authentication backends according to SPEC.
607 Calls `auth-source-search' with the :delete property in SPEC set to t.
608 The backend may not actually delete the entries.
609
610 Returns the deleted entries."
611   (auth-source-search (plist-put spec :delete t)))
612
613 (defun auth-source-search-collection (collection value)
614   "Returns t is VALUE is t or COLLECTION is t or contains VALUE."
615   (when (and (atom collection) (not (eq t collection)))
616     (setq collection (list collection)))
617
618   ;; (debug :collection collection :value value)
619   (or (eq collection t)
620       (eq value t)
621       (equal collection value)
622       (member value collection)))
623
624 (defun auth-source-forget-all-cached ()
625   "Forget all cached auth-source data."
626   (interactive)
627   (loop for sym being the symbols of password-data
628         ;; when the symbol name starts with auth-source-magic
629         when (string-match (concat "^" auth-source-magic)
630                            (symbol-name sym))
631         ;; remove that key
632         do (password-cache-remove (symbol-name sym))))
633
634 (defun auth-source-remember (spec found)
635   "Remember FOUND search results for SPEC."
636   (let ((password-cache-expiry auth-source-cache-expiry))
637     (password-cache-add
638      (concat auth-source-magic (format "%S" spec)) found)))
639
640 (defun auth-source-recall (spec)
641   "Recall FOUND search results for SPEC."
642   (password-read-from-cache
643    (concat auth-source-magic (format "%S" spec))))
644
645 (defun auth-source-forget (spec)
646   "Forget any cached data matching SPEC exactly.
647
648 This is the same SPEC you passed to `auth-source-search'.
649 Returns t or nil for forgotten or not found."
650   (password-cache-remove (concat auth-source-magic (format "%S" spec))))
651
652 ;;; (loop for sym being the symbols of password-data when (string-match (concat "^" auth-source-magic) (symbol-name sym)) collect (symbol-name sym))
653
654 ;;; (auth-source-remember '(:host "wedd") '(4 5 6))
655 ;;; (auth-source-remember '(:host "xedd") '(1 2 3))
656 ;;; (auth-source-recall '(:host "xedd"))
657 ;;; (auth-source-recall '(:host t))
658 ;;; (auth-source-forget+ :host t)
659
660 (defun* auth-source-forget+ (&rest spec &allow-other-keys)
661   "Forget any cached data matching SPEC.  Returns forgotten count.
662
663 This is not a full `auth-source-search' spec but works similarly.
664 For instance, \(:host \"myhost\" \"yourhost\") would find all the
665 cached data that was found with a search for those two hosts,
666 while \(:host t) would find all host entries."
667   (let ((count 0)
668         sname)
669     (loop for sym being the symbols of password-data
670           ;; when the symbol name matches with auth-source-magic
671           when (and (setq sname (symbol-name sym))
672                     (string-match (concat "^" auth-source-magic "\\(.+\\)")
673                                   sname)
674                     ;; and the spec matches what was stored in the cache
675                     (auth-source-specmatchp spec (read (match-string 1 sname))))
676           ;; remove that key
677           do (progn
678                (password-cache-remove sname)
679                (incf count)))
680     count))
681
682 (defun auth-source-specmatchp (spec stored)
683   (let ((keys (loop for i below (length spec) by 2
684                    collect (nth i spec))))
685     (not (eq
686           (dolist (key keys)
687             (unless (auth-source-search-collection (plist-get stored key)
688                                                    (plist-get spec key))
689               (return 'no)))
690           'no))))
691
692 ;;; Backend specific parsing: netrc/authinfo backend
693
694 (defun auth-source-ensure-strings (values)
695   (unless (listp values)
696     (setq values (list values)))
697   (mapcar (lambda (value)
698             (if (numberp value)
699                 (format "%s" value)
700               value))
701           values))
702
703 (defvar auth-source-netrc-cache nil)
704
705 ;;; (auth-source-netrc-parse "~/.authinfo.gpg")
706 (defun* auth-source-netrc-parse (&rest
707                                  spec
708                                  &key file max host user port delete
709                                  &allow-other-keys)
710   "Parse FILE and return a list of all entries in the file.
711 Note that the MAX parameter is used so we can exit the parse early."
712   (if (listp file)
713       ;; We got already parsed contents; just return it.
714       file
715     (when (file-exists-p file)
716       (setq port (auth-source-ensure-strings port))
717       (with-temp-buffer
718         (let ((tokens '("machine" "host" "default" "login" "user"
719                         "password" "account" "macdef" "force"
720                         "port" "protocol"))
721               (max (or max 5000))       ; sanity check: default to stop at 5K
722               (modified 0)
723               alist elem result pair)
724           (if (and auth-source-netrc-cache
725                    (equal (car auth-source-netrc-cache)
726                           (nth 5 (file-attributes file))))
727               (insert (base64-decode-string
728                        (rot13-string (cdr auth-source-netrc-cache))))
729             (insert-file-contents file)
730             (when (string-match "\\.gpg\\'" file)
731               ;; Store the contents of the file heavily encrypted in memory.
732               (setq auth-source-netrc-cache
733                     (cons (nth 5 (file-attributes file))
734                           (rot13-string
735                            (base64-encode-string
736                             (buffer-string)))))))
737           (goto-char (point-min))
738           ;; Go through the file, line by line.
739           (while (and (not (eobp))
740                       (> max 0))
741
742             (narrow-to-region (point) (point-at-eol))
743             ;; For each line, get the tokens and values.
744             (while (not (eobp))
745               (skip-chars-forward "\t ")
746               ;; Skip lines that begin with a "#".
747               (if (eq (char-after) ?#)
748                   (goto-char (point-max))
749                 (unless (eobp)
750                   (setq elem
751                         (if (= (following-char) ?\")
752                             (read (current-buffer))
753                           (buffer-substring
754                            (point) (progn (skip-chars-forward "^\t ")
755                                           (point)))))
756                   (cond
757                    ((equal elem "macdef")
758                     ;; We skip past the macro definition.
759                     (widen)
760                     (while (and (zerop (forward-line 1))
761                                 (looking-at "$")))
762                     (narrow-to-region (point) (point)))
763                    ((member elem tokens)
764                     ;; Tokens that don't have a following value are ignored,
765                     ;; except "default".
766                     (when (and pair (or (cdr pair)
767                                         (equal (car pair) "default")))
768                       (push pair alist))
769                     (setq pair (list elem)))
770                    (t
771                     ;; Values that haven't got a preceding token are ignored.
772                     (when pair
773                       (setcdr pair elem)
774                       (push pair alist)
775                       (setq pair nil)))))))
776
777             (when (and alist
778                        (> max 0)
779                        (auth-source-search-collection
780                         host
781                         (or
782                          (aget alist "machine")
783                          (aget alist "host")
784                          t))
785                        (auth-source-search-collection
786                         user
787                         (or
788                          (aget alist "login")
789                          (aget alist "account")
790                          (aget alist "user")
791                          t))
792                        (auth-source-search-collection
793                         port
794                         (or
795                          (aget alist "port")
796                          (aget alist "protocol")
797                          t)))
798               (decf max)
799               (push (nreverse alist) result)
800               ;; to delete a line, we just comment it out
801               (when delete
802                 (goto-char (point-min))
803                 (insert "#")
804                 (incf modified)))
805             (setq alist nil
806                   pair nil)
807             (widen)
808             (forward-line 1))
809
810           (when (< 0 modified)
811             (when auth-source-gpg-encrypt-to
812               ;; (see bug#7487) making `epa-file-encrypt-to' local to
813               ;; this buffer lets epa-file skip the key selection query
814               ;; (see the `local-variable-p' check in
815               ;; `epa-file-write-region').
816               (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
817                 (make-local-variable 'epa-file-encrypt-to))
818               (if (listp auth-source-gpg-encrypt-to)
819                   (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
820
821             ;; ask AFTER we've successfully opened the file
822             (when (y-or-n-p (format "Save file %s? (%d modifications)"
823                                     file modified))
824               (write-region (point-min) (point-max) file nil 'silent)
825               (auth-source-do-debug
826                "auth-source-netrc-parse: modified %d lines in %s"
827                modified file)))
828
829           (nreverse result))))))
830
831 (defun auth-source-netrc-normalize (alist)
832   (mapcar (lambda (entry)
833             (let (ret item)
834               (while (setq item (pop entry))
835                 (let ((k (car item))
836                       (v (cdr item)))
837
838                   ;; apply key aliases
839                   (setq k (cond ((member k '("machine")) "host")
840                                 ((member k '("login" "account")) "user")
841                                 ((member k '("protocol")) "port")
842                                 ((member k '("password")) "secret")
843                                 (t k)))
844
845                   ;; send back the secret in a function (lexical binding)
846                   (when (equal k "secret")
847                     (setq v (lexical-let ((v v))
848                               (lambda () v))))
849
850                   (setq ret (plist-put ret
851                                        (intern (concat ":" k))
852                                        v))
853                   ))
854               ret))
855           alist))
856
857 ;;; (setq secret (plist-get (nth 0 (auth-source-search :host t :type 'netrc :K 1 :max 1)) :secret))
858 ;;; (funcall secret)
859
860 (defun* auth-source-netrc-search (&rest
861                                   spec
862                                   &key backend create delete
863                                   type max host user port
864                                   &allow-other-keys)
865 "Given a property list SPEC, return search matches from the :backend.
866 See `auth-source-search' for details on SPEC."
867   ;; just in case, check that the type is correct (null or same as the backend)
868   (assert (or (null type) (eq type (oref backend type)))
869           t "Invalid netrc search: %s %s")
870
871   (let ((results (auth-source-netrc-normalize
872                   (auth-source-netrc-parse
873                    :max max
874                    :delete delete
875                    :file (oref backend source)
876                    :host (or host t)
877                    :user (or user t)
878                    :port (or port t)))))
879
880     ;; if we need to create an entry AND none were found to match
881     (when (and create
882                (= 0 (length results)))
883
884       ;; create based on the spec and record the value
885       (setq results (or
886                      ;; if the user did not want to create the entry
887                      ;; in the file, it will be returned
888                      (apply (slot-value backend 'create-function) spec)
889                      ;; if not, we do the search again without :create
890                      ;; to get the updated data.
891
892                      ;; the result will be returned, even if the search fails
893                      (apply 'auth-source-netrc-search
894                             (plist-put spec :create nil)))))
895     results))
896
897 ;;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t)
898 ;;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t :create-extra-keys '((A "default A") (B)))
899
900 (defun* auth-source-netrc-create (&rest spec
901                                         &key backend
902                                         secret host user port create
903                                         &allow-other-keys)
904   (let* ((base-required '(host user port secret))
905          ;; we know (because of an assertion in auth-source-search) that the
906          ;; :create parameter is either t or a list (which includes nil)
907          (create-extra (if (eq t create) nil create))
908          (required (append base-required create-extra))
909          (file (oref backend source))
910          (add "")
911          (show "")
912          ;; `valist' is an alist
913          valist
914          ;; `artificial' will be returned if no creation is needed
915          artificial)
916
917     ;; only for base required elements (defined as function parameters):
918     ;; fill in the valist with whatever data we may have from the search
919     ;; we complete the first value if it's a list and use the value otherwise
920     (dolist (br base-required)
921       (when (symbol-value br)
922         (let ((br-choice (cond
923                           ;; all-accepting choice (predicate is t)
924                           ((eq t (symbol-value br)) nil)
925                           ;; just the value otherwise
926                           (t (symbol-value br)))))
927           (when br-choice
928             (aput 'valist br br-choice)))))
929
930     ;; for extra required elements, see if the spec includes a value for them
931     (dolist (er create-extra)
932       (let ((name (concat ":" (symbol-name er)))
933             (keys (loop for i below (length spec) by 2
934                         collect (nth i spec))))
935         (dolist (k keys)
936           (when (equal (symbol-name k) name)
937             (aput 'valist er (plist-get spec k))))))
938
939     ;; for each required element
940     (dolist (r required)
941       (let* ((data (aget valist r))
942              (given-default (aget auth-source-creation-defaults r))
943              ;; the defaults are simple
944              (default (cond
945                        ((and (not given-default) (eq r 'user))
946                         (user-login-name))
947                        ;; note we need this empty string
948                        ((and (not given-default) (eq r 'port))
949                         "")
950                        (t given-default)))
951              ;; the prompt's default string depends on the data so far
952              (default-string (if (and default (< 0 (length default)))
953                                  (format " (default %s)" default)
954                                " (no default)"))
955              ;; the prompt should also show what's entered so far
956              (user-value (aget valist 'user))
957              (host-value (aget valist 'host))
958              (port-value (aget valist 'port))
959              ;; note this handles lists by just printing them
960              ;; later we allow the user to use completing-read to pick
961              (info-so-far (concat (if user-value
962                                       (format "%s@" user-value)
963                                     "[USER?]")
964                                   (if host-value
965                                       (format "%s" host-value)
966                                     "[HOST?]")
967                                   (if port-value
968                                       ;; this distinguishes protocol between
969                                       (if (zerop (length port-value))
970                                           "" ; 'entered as "no default"' vs.
971                                         (format ":%s" port-value)) ; given
972                                     ;; and this is when the protocol is unknown
973                                     "[PORT?]"))))
974
975         ;; now prompt if the search SPEC did not include a required key;
976         ;; take the result and put it in `data' AND store it in `valist'
977         (aput 'valist r
978               (setq data
979                     (cond
980                      ((and (null data) (eq r 'secret))
981                       ;; special case prompt for passwords
982                       (read-passwd (format "Password for %s: " info-so-far)))
983                      ((null data)
984                       (read-string
985                        (format "Enter %s for %s%s: "
986                                r info-so-far default-string)
987                        nil nil default))
988                      ((listp data)
989                       (completing-read
990                        (format "Enter %s for %s (TAB to see the choices): "
991                                r info-so-far)
992                        data
993                        nil              ; no predicate
994                        t                ; require a match
995                        ;; note the default is nil, but if the user
996                        ;; hits RET we'll get "", which is handled OK later
997                        nil))
998                      (t data))))
999
1000         (when data
1001           (setq artificial (plist-put artificial
1002                                       (intern (concat ":" (symbol-name r)))
1003                                       (if (eq r 'secret)
1004                                           (lexical-let ((data data))
1005                                             (lambda () data))
1006                                         data))))
1007
1008         ;; when r is not an empty string...
1009         (when (and (stringp data)
1010                    (< 0 (length data)))
1011           (let ((printer (lambda (hide)
1012                            ;; append the key (the symbol name of r)
1013                            ;; and the value in r
1014                            (format "%s%s %S"
1015                                    ;; prepend a space
1016                                    (if (zerop (length add)) "" " ")
1017                                    ;; remap auth-source tokens to netrc
1018                                    (case r
1019                                      ('user "login")
1020                                      ('host "machine")
1021                                      ('secret "password")
1022                                      ('port "port") ; redundant but clearer
1023                                      (t (symbol-name r)))
1024                                    ;; the value will be printed in %S format
1025                                    (if (and hide (eq r 'secret))
1026                                        "HIDDEN_SECRET"
1027                                      data)))))
1028             (setq add (concat add (funcall printer nil)))
1029             (setq show (concat show (funcall printer t)))))))
1030
1031     (with-temp-buffer
1032       (when (file-exists-p file)
1033         (insert-file-contents file))
1034       (when auth-source-gpg-encrypt-to
1035         ;; (see bug#7487) making `epa-file-encrypt-to' local to
1036         ;; this buffer lets epa-file skip the key selection query
1037         ;; (see the `local-variable-p' check in
1038         ;; `epa-file-write-region').
1039         (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
1040           (make-local-variable 'epa-file-encrypt-to))
1041         (if (listp auth-source-gpg-encrypt-to)
1042             (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
1043       (goto-char (point-max))
1044
1045       ;; ask AFTER we've successfully opened the file
1046       (if (y-or-n-p (format "Add to file %s: line [%s]" file show))
1047           (progn
1048             (unless (bolp)
1049               (insert "\n"))
1050             (insert add "\n")
1051             (write-region (point-min) (point-max) file nil 'silent)
1052             (auth-source-do-debug
1053              "auth-source-netrc-create: wrote 1 new line to %s"
1054              file)
1055             nil)
1056         (list artificial)))))
1057
1058 ;;; Backend specific parsing: Secrets API backend
1059
1060 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1 :create t))
1061 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1 :delete t))
1062 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1))
1063 ;;; (let ((auth-sources '(default))) (auth-source-search))
1064 ;;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1))
1065 ;;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1 :signon_realm "https://git.gnus.org/Git"))
1066
1067 (defun* auth-source-secrets-search (&rest
1068                                     spec
1069                                     &key backend create delete label
1070                                     type max host user port
1071                                     &allow-other-keys)
1072   "Search the Secrets API; spec is like `auth-source'.
1073
1074 The :label key specifies the item's label.  It is the only key
1075 that can specify a substring.  Any :label value besides a string
1076 will allow any label.
1077
1078 All other search keys must match exactly.  If you need substring
1079 matching, do a wider search and narrow it down yourself.
1080
1081 You'll get back all the properties of the token as a plist.
1082
1083 Here's an example that looks for the first item in the 'Login'
1084 Secrets collection:
1085
1086  \(let ((auth-sources '(\"secrets:Login\")))
1087     (auth-source-search :max 1)
1088
1089 Here's another that looks for the first item in the 'Login'
1090 Secrets collection whose label contains 'gnus':
1091
1092  \(let ((auth-sources '(\"secrets:Login\")))
1093     (auth-source-search :max 1 :label \"gnus\")
1094
1095 And this one looks for the first item in the 'Login' Secrets
1096 collection that's a Google Chrome entry for the git.gnus.org site
1097 authentication tokens:
1098
1099  \(let ((auth-sources '(\"secrets:Login\")))
1100     (auth-source-search :max 1 :signon_realm \"https://git.gnus.org/Git\"))
1101 "
1102
1103   ;; TODO
1104   (assert (not create) nil
1105           "The Secrets API auth-source backend doesn't support creation yet")
1106   ;; TODO
1107   ;; (secrets-delete-item coll elt)
1108   (assert (not delete) nil
1109           "The Secrets API auth-source backend doesn't support deletion yet")
1110
1111   (let* ((coll (oref backend source))
1112          (max (or max 5000))     ; sanity check: default to stop at 5K
1113          (ignored-keys '(:create :delete :max :backend :label))
1114          (search-keys (loop for i below (length spec) by 2
1115                             unless (memq (nth i spec) ignored-keys)
1116                             collect (nth i spec)))
1117          ;; build a search spec without the ignored keys
1118          ;; if a search key is nil or t (match anything), we skip it
1119          (search-spec (apply 'append (mapcar
1120                                       (lambda (k)
1121                                         (if (or (null (plist-get spec k))
1122                                                 (eq t (plist-get spec k)))
1123                                             nil
1124                                           (list k (plist-get spec k))))
1125                               search-keys)))
1126          ;; needed keys (always including host, login, port, and secret)
1127          (returned-keys (mm-delete-duplicates (append
1128                                                '(:host :login :port :secret)
1129                                                search-keys)))
1130          (items (loop for item in (apply 'secrets-search-items coll search-spec)
1131                       unless (and (stringp label)
1132                                   (not (string-match label item)))
1133                       collect item))
1134          ;; TODO: respect max in `secrets-search-items', not after the fact
1135          (items (butlast items (- (length items) max)))
1136          ;; convert the item name to a full plist
1137          (items (mapcar (lambda (item)
1138                           (append
1139                            ;; make an entry for the secret (password) element
1140                            (list
1141                             :secret
1142                             (lexical-let ((v (secrets-get-secret coll item)))
1143                               (lambda () v)))
1144                            ;; rewrite the entry from ((k1 v1) (k2 v2)) to plist
1145                            (apply 'append
1146                                   (mapcar (lambda (entry)
1147                                             (list (car entry) (cdr entry)))
1148                                           (secrets-get-attributes coll item)))))
1149                         items))
1150          ;; ensure each item has each key in `returned-keys'
1151          (items (mapcar (lambda (plist)
1152                           (append
1153                            (apply 'append
1154                                   (mapcar (lambda (req)
1155                                             (if (plist-get plist req)
1156                                                 nil
1157                                               (list req nil)))
1158                                           returned-keys))
1159                            plist))
1160                         items)))
1161     items))
1162
1163 (defun* auth-source-secrets-create (&rest
1164                                     spec
1165                                     &key backend type max host user port
1166                                     &allow-other-keys)
1167   ;; TODO
1168   ;; (apply 'secrets-create-item (auth-get-source entry) name passwd spec)
1169   (debug spec))
1170
1171 ;;; older API
1172
1173 ;;; (auth-source-user-or-password '("login" "password") "imap.myhost.com" t "tzz")
1174
1175 ;; deprecate the old interface
1176 (make-obsolete 'auth-source-user-or-password
1177                'auth-source-search "Emacs 24.1")
1178 (make-obsolete 'auth-source-forget-user-or-password
1179                'auth-source-forget "Emacs 24.1")
1180
1181 (defun auth-source-user-or-password
1182   (mode host port &optional username create-missing delete-existing)
1183   "Find MODE (string or list of strings) matching HOST and PORT.
1184
1185 DEPRECATED in favor of `auth-source-search'!
1186
1187 USERNAME is optional and will be used as \"login\" in a search
1188 across the Secret Service API (see secrets.el) if the resulting
1189 items don't have a username.  This means that if you search for
1190 username \"joe\" and it matches an item but the item doesn't have
1191 a :user attribute, the username \"joe\" will be returned.
1192
1193 A non nil DELETE-EXISTING means deleting any matching password
1194 entry in the respective sources.  This is useful only when
1195 CREATE-MISSING is non nil as well; the intended use case is to
1196 remove wrong password entries.
1197
1198 If no matching entry is found, and CREATE-MISSING is non nil,
1199 the password will be retrieved interactively, and it will be
1200 stored in the password database which matches best (see
1201 `auth-sources').
1202
1203 MODE can be \"login\" or \"password\"."
1204   (auth-source-do-debug
1205    "auth-source-user-or-password: DEPRECATED get %s for %s (%s) + user=%s"
1206    mode host port username)
1207
1208   (let* ((listy (listp mode))
1209          (mode (if listy mode (list mode)))
1210          (cname (if username
1211                     (format "%s %s:%s %s" mode host port username)
1212                   (format "%s %s:%s" mode host port)))
1213          (search (list :host host :port port))
1214          (search (if username (append search (list :user username)) search))
1215          (search (if create-missing
1216                      (append search (list :create t))
1217                    search))
1218          (search (if delete-existing
1219                      (append search (list :delete t))
1220                    search))
1221          ;; (found (if (not delete-existing)
1222          ;;            (gethash cname auth-source-cache)
1223          ;;          (remhash cname auth-source-cache)
1224          ;;          nil)))
1225          (found nil))
1226     (if found
1227         (progn
1228           (auth-source-do-debug
1229            "auth-source-user-or-password: DEPRECATED cached %s=%s for %s (%s) + %s"
1230            mode
1231            ;; don't show the password
1232            (if (and (member "password" mode) t)
1233                "SECRET"
1234              found)
1235            host port username)
1236           found)                        ; return the found data
1237       ;; else, if not found, search with a max of 1
1238       (let ((choice (nth 0 (apply 'auth-source-search
1239                                   (append '(:max 1) search)))))
1240         (when choice
1241           (dolist (m mode)
1242             (cond
1243              ((equal "password" m)
1244               (push (if (plist-get choice :secret)
1245                       (funcall (plist-get choice :secret))
1246                     nil) found))
1247              ((equal "login" m)
1248               (push (plist-get choice :user) found)))))
1249         (setq found (nreverse found))
1250         (setq found (if listy found (car-safe found)))))
1251
1252         found))
1253
1254 (provide 'auth-source)
1255
1256 ;;; auth-source.el ends here