auth-source.el (auth-source-secrets-search): Use mm-delete-duplicates instead of...
[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    (protocol :initarg :protocol
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 t
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")
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\".
187
188 See the auth.info manual for details.
189
190 Each entry is the authentication type with optional properties.
191
192 It's best to customize this with `M-x customize-variable' because the choices
193 can get pretty complex."
194   :group 'auth-source
195   :version "24.1" ;; No Gnus
196   :type `(repeat :tag "Authentication Sources"
197                  (choice
198                   (string :tag "Just a file")
199                   (const :tag "Default Secrets API Collection" 'default)
200                   (const :tag "Login Secrets API Collection" "secrets:Login")
201                   (const :tag "Temp Secrets API Collection" "secrets:session")
202                   (list :tag "Source definition"
203                         (const :format "" :value :source)
204                         (choice :tag "Authentication backend choice"
205                                 (string :tag "Authentication Source (file)")
206                                 (list
207                                  :tag "Secret Service API/KWallet/GNOME Keyring"
208                                  (const :format "" :value :secrets)
209                                  (choice :tag "Collection to use"
210                                          (string :tag "Collection name")
211                                          (const :tag "Default" 'default)
212                                          (const :tag "Login" "Login")
213                                          (const
214                                           :tag "Temporary" "session"))))
215                         (repeat :tag "Extra Parameters" :inline t
216                                 (choice :tag "Extra parameter"
217                                         (list
218                                          :tag "Host"
219                                          (const :format "" :value :host)
220                                          (choice :tag "Host (machine) choice"
221                                                  (const :tag "Any" t)
222                                                  (regexp
223                                                   :tag "Regular expression")))
224                                         (list
225                                          :tag "Protocol"
226                                          (const :format "" :value :protocol)
227                                          (choice
228                                           :tag "Protocol"
229                                           (const :tag "Any" t)
230                                           ,@auth-source-protocols-customize))
231                                         (list :tag "User" :inline t
232                                               (const :format "" :value :user)
233                                               (choice :tag "Personality/Username"
234                                                       (const :tag "Any" t)
235                                                       (string :tag "Name")))))))))
236
237 (defcustom auth-source-gpg-encrypt-to t
238   "List of recipient keys that `authinfo.gpg' encrypted to.
239 If the value is not a list, symmetric encryption will be used."
240   :group 'auth-source
241   :version "24.1" ;; No Gnus
242   :type '(choice (const :tag "Symmetric encryption" t)
243                  (repeat :tag "Recipient public keys"
244                          (string :tag "Recipient public key"))))
245
246 ;; temp for debugging
247 ;; (unintern 'auth-source-protocols)
248 ;; (unintern 'auth-sources)
249 ;; (customize-variable 'auth-sources)
250 ;; (setq auth-sources nil)
251 ;; (format "%S" auth-sources)
252 ;; (customize-variable 'auth-source-protocols)
253 ;; (setq auth-source-protocols nil)
254 ;; (format "%S" auth-source-protocols)
255 ;; (auth-source-pick nil :host "a" :port 'imap)
256 ;; (auth-source-user-or-password "login" "imap.myhost.com" 'imap)
257 ;; (auth-source-user-or-password "password" "imap.myhost.com" 'imap)
258 ;; (auth-source-user-or-password-imap "login" "imap.myhost.com")
259 ;; (auth-source-user-or-password-imap "password" "imap.myhost.com")
260 ;; (auth-source-protocol-defaults 'imap)
261
262 ;; (let ((auth-source-debug 'debug)) (auth-source-do-debug "hello"))
263 ;; (let ((auth-source-debug t)) (auth-source-do-debug "hello"))
264 ;; (let ((auth-source-debug nil)) (auth-source-do-debug "hello"))
265 (defun auth-source-do-debug (&rest msg)
266   (when auth-source-debug
267     (apply 'auth-source-do-warn msg)))
268
269 (defun auth-source-do-warn (&rest msg)
270   (apply
271     ;; set logger to either the function in auth-source-debug or 'message
272     ;; note that it will be 'message if auth-source-debug is nil
273    (if (functionp auth-source-debug)
274        auth-source-debug
275      'message)
276    msg))
277
278
279 ;; (auth-source-pick nil :host "any" :protocol 'imap :user "joe")
280 ;; (auth-source-pick t :host "any" :protocol 'imap :user "joe")
281 ;; (setq auth-sources '((:source (:secrets default) :host t :protocol t :user "joe")
282 ;;                   (:source (:secrets "session") :host t :protocol t :user "joe")
283 ;;                   (:source (:secrets "Login") :host t :protocol t)
284 ;;                   (:source "~/.authinfo.gpg" :host t :protocol t)))
285
286 ;; (setq auth-sources '((:source (:secrets default) :host t :protocol t :user "joe")
287 ;;                   (:source (:secrets "session") :host t :protocol t :user "joe")
288 ;;                   (:source (:secrets "Login") :host t :protocol t)
289 ;;                   ))
290
291 ;; (setq auth-sources '((:source "~/.authinfo.gpg" :host t :protocol t)))
292
293 ;; (auth-source-backend-parse "myfile.gpg")
294 ;; (auth-source-backend-parse 'default)
295 ;; (auth-source-backend-parse "secrets:Login")
296
297 (defun auth-source-backend-parse (entry)
298   "Creates an auth-source-backend from an ENTRY in `auth-sources'."
299   (auth-source-backend-parse-parameters
300    entry
301    (cond
302     ;; take 'default and recurse to get it as a Secrets API default collection
303     ;; matching any user, host, and protocol
304     ((eq entry 'default)
305      (auth-source-backend-parse '(:source (:secrets default))))
306     ;; take secrets:XYZ and recurse to get it as Secrets API collection "XYZ"
307     ;; matching any user, host, and protocol
308     ((and (stringp entry) (string-match "^secrets:\\(.+\\)" entry))
309      (auth-source-backend-parse `(:source (:secrets ,(match-string 1 entry)))))
310     ;; take just a file name and recurse to get it as a netrc file
311     ;; matching any user, host, and protocol
312     ((stringp entry)
313      (auth-source-backend-parse `(:source ,entry)))
314
315     ;; a file name with parameters
316     ((stringp (plist-get entry :source))
317      (auth-source-backend
318       (plist-get entry :source)
319       :source (plist-get entry :source)
320       :type 'netrc
321       :search-function 'auth-source-netrc-search
322       :create-function 'auth-source-netrc-create))
323
324     ;; the Secrets API.  We require the package, in order to have a
325     ;; defined value for `secrets-enabled'.
326     ((and
327       (not (null (plist-get entry :source))) ; the source must not be nil
328       (listp (plist-get entry :source))      ; and it must be a list
329       (require 'secrets nil t)               ; and we must load the Secrets API
330       secrets-enabled)                       ; and that API must be enabled
331
332      ;; the source is either the :secrets key in ENTRY or
333      ;; if that's missing or nil, it's "session"
334      (let ((source (or (plist-get (plist-get entry :source) :secrets)
335                        "session")))
336
337        ;; if the source is a symbol, we look for the alias named so,
338        ;; and if that alias is missing, we use "Login"
339        (when (symbolp source)
340          (setq source (or (secrets-get-alias (symbol-name source))
341                           "Login")))
342
343        (if (featurep 'secrets)
344            (auth-source-backend
345             (format "Secrets API (%s)" source)
346             :source source
347             :type 'secrets
348             :search-function 'auth-source-secrets-search
349             :create-function 'auth-source-secrets-create)
350          (auth-source-do-warn
351           "auth-source-backend-parse: no Secrets API, ignoring spec: %S" entry)
352          (auth-source-backend
353           (format "Ignored Secrets API (%s)" source)
354           :source ""
355           :type 'ignore))))
356
357     ;; none of them
358     (t
359      (auth-source-do-warn
360       "auth-source-backend-parse: invalid backend spec: %S" entry)
361      (auth-source-backend
362       "Empty"
363       :source ""
364       :type 'ignore)))))
365
366 (defun auth-source-backend-parse-parameters (entry backend)
367   "Fills in the extra auth-source-backend parameters of ENTRY.
368 Using the plist ENTRY, get the :host, :protocol, and :user search
369 parameters.  Accepts :port as an alias to :protocol."
370   (let ((entry (if (stringp entry)
371                    nil
372                  entry))
373         val)
374     (when (setq val (plist-get entry :host))
375       (oset backend host val))
376     (when (setq val (plist-get entry :user))
377       (oset backend user val))
378     ;; accept :port as an alias for :protocol
379     (when (setq val (or (plist-get entry :protocol) (plist-get entry :port)))
380       (oset backend protocol 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 protocol 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, :protocol, 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 protocol 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 protocol.  The host will be
430  'mine'.  We prompt for the user with default 'defaultUser' and
431  for the protocol without a default.  We will not prompt for A, Q,
432  or P.  The resulting token will only have keys user, host, and
433  protocol.\"
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 protocol.  The host will be
459  'nonesuch' and Q will be 'qqqq'.  We prompt for A with default
460  'default A', for B and protocol 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, protocol, 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 first one is used for creation.  So :host (X Y Z) would create a
468 token for host X, for instance.
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 :protocol (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 :protocol :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)
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       (dolist (backend filtered-backends)
544         (setq found-here (apply
545                           (slot-value backend 'search-function)
546                           :backend backend
547                           :create create
548                           :delete delete
549                           spec))
550
551         ;; if max is 0, as soon as we find something, return it
552         (when (and (zerop max) (> 0 (length found-here)))
553           (return t))
554
555         ;; decrement the goal by the number of new results
556         (decf goal (length found-here))
557         ;; and append the new results to the full list
558         (setq found (append found found-here))
559
560         (auth-source-do-debug
561          "auth-source-search: found %d results (max %d/%d) in %S matching %S"
562          (length found-here) max goal backend spec)
563
564         ;; return full list if the goal is 0 or negative
565         (when (zerop (max 0 goal))
566           (return found))
567
568         ;; change the :max parameter in the spec to the goal
569         (setq spec (plist-put spec :max goal)))
570
571       (when (and found auth-source-do-cache)
572         (auth-source-remember spec found)))
573
574       found))
575
576 ;;; (auth-source-search :max 1)
577 ;;; (funcall (plist-get (nth 0 (auth-source-search :max 1)) :secret))
578 ;;; (auth-source-search :host "nonesuch" :type 'netrc :K 1)
579 ;;; (auth-source-search :host "nonesuch" :type 'secrets)
580
581 (defun* auth-source-delete (&rest spec
582                                   &key delete
583                                   &allow-other-keys)
584   "Delete entries from the authentication backends according to SPEC.
585 Calls `auth-source-search' with the :delete property in SPEC set to t.
586 The backend may not actually delete the entries.
587
588 Returns the deleted entries."
589   (auth-source-search (plist-put spec :delete t)))
590
591 (defun auth-source-search-collection (collection value)
592   "Returns t is VALUE is t or COLLECTION is t or contains VALUE."
593   (when (and (atom collection) (not (eq t collection)))
594     (setq collection (list collection)))
595
596   ;; (debug :collection collection :value value)
597   (or (eq collection t)
598       (eq value t)
599       (equal collection value)
600       (member value collection)))
601
602 (defun auth-source-forget-all-cached ()
603   "Forget all cached auth-source data."
604   (interactive)
605   (loop for sym being the symbols of password-data
606         ;; when the symbol name starts with auth-source-magic
607         when (string-match (concat "^" auth-source-magic)
608                            (symbol-name sym))
609         ;; remove that key
610         do (password-cache-remove (symbol-name sym))))
611
612 (defun auth-source-remember (spec found)
613   "Remember FOUND search results for SPEC."
614   (let ((password-cache-expiry auth-source-cache-expiry))
615     (password-cache-add
616      (concat auth-source-magic (format "%S" spec)) found)))
617
618 (defun auth-source-recall (spec)
619   "Recall FOUND search results for SPEC."
620   (password-read-from-cache
621    (concat auth-source-magic (format "%S" spec))))
622
623 (defun auth-source-forget (spec)
624   "Forget any cached data matching SPEC exactly.
625
626 This is the same SPEC you passed to `auth-source-search'.
627 Returns t or nil for forgotten or not found."
628   (password-cache-remove (concat auth-source-magic (format "%S" spec))))
629
630 ;;; (loop for sym being the symbols of password-data when (string-match (concat "^" auth-source-magic) (symbol-name sym)) collect (symbol-name sym))
631
632 ;;; (auth-source-remember '(:host "wedd") '(4 5 6))
633 ;;; (auth-source-remember '(:host "xedd") '(1 2 3))
634 ;;; (auth-source-recall '(:host "xedd"))
635 ;;; (auth-source-recall '(:host t))
636 ;;; (auth-source-forget+ :host t)
637
638 (defun* auth-source-forget+ (&rest spec &allow-other-keys)
639   "Forget any cached data matching SPEC.  Returns forgotten count.
640
641 This is not a full `auth-source-search' spec but works similarly.
642 For instance, \(:host \"myhost\" \"yourhost\") would find all the
643 cached data that was found with a search for those two hosts,
644 while \(:host t) would find all host entries."
645   (let ((count 0)
646         sname)
647     (loop for sym being the symbols of password-data
648           ;; when the symbol name matches with auth-source-magic
649           when (and (setq sname (symbol-name sym))
650                     (string-match (concat "^" auth-source-magic "\\(.+\\)")
651                                   sname)
652                     ;; and the spec matches what was stored in the cache
653                     (auth-source-specmatchp spec (read (match-string 1 sname))))
654           ;; remove that key
655           do (progn
656                (password-cache-remove sname)
657                (incf count)))
658     count))
659
660 (defun auth-source-specmatchp (spec stored)
661   (let ((keys (loop for i below (length spec) by 2
662                    collect (nth i spec))))
663     (not (eq
664           (dolist (key keys)
665             (unless (auth-source-search-collection (plist-get stored key)
666                                                    (plist-get spec key))
667               (return 'no)))
668           'no))))
669
670 ;;; Backend specific parsing: netrc/authinfo backend
671
672 ;;; (auth-source-netrc-parse "~/.authinfo.gpg")
673 (defun* auth-source-netrc-parse (&rest
674                                  spec
675                                  &key file max host user protocol delete
676                                  &allow-other-keys)
677   "Parse FILE and return a list of all entries in the file.
678 Note that the MAX parameter is used so we can exit the parse early."
679   (if (listp file)
680       ;; We got already parsed contents; just return it.
681       file
682     (when (file-exists-p file)
683       (with-temp-buffer
684         (let ((tokens '("machine" "host" "default" "login" "user"
685                         "password" "account" "macdef" "force"
686                         "port" "protocol"))
687               (max (or max 5000))       ; sanity check: default to stop at 5K
688               (modified 0)
689               alist elem result pair)
690           (insert-file-contents file)
691           (goto-char (point-min))
692           ;; Go through the file, line by line.
693           (while (and (not (eobp))
694                       (> max 0))
695
696             (narrow-to-region (point) (point-at-eol))
697             ;; For each line, get the tokens and values.
698             (while (not (eobp))
699               (skip-chars-forward "\t ")
700               ;; Skip lines that begin with a "#".
701               (if (eq (char-after) ?#)
702                   (goto-char (point-max))
703                 (unless (eobp)
704                   (setq elem
705                         (if (= (following-char) ?\")
706                             (read (current-buffer))
707                           (buffer-substring
708                            (point) (progn (skip-chars-forward "^\t ")
709                                           (point)))))
710                   (cond
711                    ((equal elem "macdef")
712                     ;; We skip past the macro definition.
713                     (widen)
714                     (while (and (zerop (forward-line 1))
715                                 (looking-at "$")))
716                     (narrow-to-region (point) (point)))
717                    ((member elem tokens)
718                     ;; Tokens that don't have a following value are ignored,
719                     ;; except "default".
720                     (when (and pair (or (cdr pair)
721                                         (equal (car pair) "default")))
722                       (push pair alist))
723                     (setq pair (list elem)))
724                    (t
725                     ;; Values that haven't got a preceding token are ignored.
726                     (when pair
727                       (setcdr pair elem)
728                       (push pair alist)
729                       (setq pair nil)))))))
730
731             (when (and alist
732                        (> max 0)
733                        (auth-source-search-collection
734                         host
735                         (or
736                          (aget alist "machine")
737                          (aget alist "host")))
738                        (auth-source-search-collection
739                         user
740                         (or
741                          (aget alist "login")
742                          (aget alist "account")
743                          (aget alist "user")))
744                        (auth-source-search-collection
745                         protocol
746                         (or
747                          (aget alist "port")
748                          (aget alist "protocol"))))
749               (decf max)
750               (push (nreverse alist) result)
751               ;; to delete a line, we just comment it out
752               (when delete
753                 (goto-char (point-min))
754                 (insert "#")
755                 (incf modified)))
756             (setq alist nil
757                   pair nil)
758             (widen)
759             (forward-line 1))
760
761           (when (< 0 modified)
762             (when auth-source-gpg-encrypt-to
763               ;; (see bug#7487) making `epa-file-encrypt-to' local to
764               ;; this buffer lets epa-file skip the key selection query
765               ;; (see the `local-variable-p' check in
766               ;; `epa-file-write-region').
767               (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
768                 (make-local-variable 'epa-file-encrypt-to))
769               (if (listp auth-source-gpg-encrypt-to)
770                   (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
771
772             ;; ask AFTER we've successfully opened the file
773             (when (y-or-n-p (format "Save file %s? (%d modifications)"
774                                     file modified))
775               (write-region (point-min) (point-max) file nil 'silent)
776               (auth-source-do-debug
777                "auth-source-netrc-parse: modified %d lines in %s"
778                modified file)))
779
780           (nreverse result))))))
781
782 (defun auth-source-netrc-normalize (alist)
783   (mapcar (lambda (entry)
784             (let (ret item)
785               (while (setq item (pop entry))
786                 (let ((k (car item))
787                       (v (cdr item)))
788
789                   ;; apply key aliases
790                   (setq k (cond ((member k '("machine")) "host")
791                                 ((member k '("login" "account")) "user")
792                                 ((member k '("protocol")) "port")
793                                 ((member k '("password")) "secret")
794                                 (t k)))
795
796                   ;; send back the secret in a function (lexical binding)
797                   (when (equal k "secret")
798                     (setq v (lexical-let ((v v))
799                               (lambda () v))))
800
801                   (setq ret (plist-put ret
802                                        (intern (concat ":" k))
803                                        v))
804                   ))
805               ret))
806           alist))
807
808 ;;; (setq secret (plist-get (nth 0 (auth-source-search :host t :type 'netrc :K 1 :max 1)) :secret))
809 ;;; (funcall secret)
810
811 (defun* auth-source-netrc-search (&rest
812                                   spec
813                                   &key backend create delete
814                                   type max host user protocol
815                                   &allow-other-keys)
816 "Given a property list SPEC, return search matches from the :backend.
817 See `auth-source-search' for details on SPEC."
818   ;; just in case, check that the type is correct (null or same as the backend)
819   (assert (or (null type) (eq type (oref backend type)))
820           t "Invalid netrc search: %s %s")
821
822   (let ((results (auth-source-netrc-normalize
823                   (auth-source-netrc-parse
824                    :max max
825                    :delete delete
826                    :file (oref backend source)
827                    :host (or host t)
828                    :user (or user t)
829                    :protocol (or protocol t)))))
830
831     ;; if we need to create an entry AND none were found to match
832     (when (and create
833                (= 0 (length results)))
834
835       ;; create based on the spec and record the value
836       (setq results (or
837                      ;; if the user did not want to create the entry
838                      ;; in the file, it will be returned
839                      (apply (slot-value backend 'create-function) spec)
840                      ;; if not, we do the search again without :create
841                      ;; to get the updated data.
842
843                      ;; the result will be returned, even if the search fails
844                      (apply 'auth-source-netrc-search
845                             (plist-put spec :create nil)))))
846     results))
847
848 ;;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t)
849 ;;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t :create-extra-keys '((A "default A") (B)))
850
851 (defun* auth-source-netrc-create (&rest spec
852                                         &key backend
853                                         secret host user protocol create
854                                         &allow-other-keys)
855   (let* ((base-required '(host user protocol secret))
856          ;; we know (because of an assertion in auth-source-search) that the
857          ;; :create parameter is either t or a list (which includes nil)
858          (create-extra (if (eq t create) nil create))
859          (required (append base-required create-extra))
860          (file (oref backend source))
861          (add "")
862          ;; `valist' is an alist
863          valist
864          ;; `artificial' will be returned if no creation is needed
865          artificial)
866
867     ;; only for base required elements (defined as function parameters):
868     ;; fill in the valist with whatever data we may have from the search
869     ;; we take the first value if it's a list, the whole value otherwise
870     (dolist (br base-required)
871       (when (symbol-value br)
872         (aput 'valist br (if (listp (symbol-value br))
873                              (nth 0 (symbol-value br))
874                            (symbol-value br)))))
875
876     ;; for extra required elements, see if the spec includes a value for them
877     (dolist (er create-extra)
878       (let ((name (concat ":" (symbol-name er)))
879             (keys (loop for i below (length spec) by 2
880                         collect (nth i spec))))
881         (dolist (k keys)
882           (when (equal (symbol-name k) name)
883             (aput 'valist er (plist-get spec k))))))
884
885     ;; for each required element
886     (dolist (r required)
887       (let* ((data (aget valist r))
888              (given-default (aget auth-source-creation-defaults r))
889              ;; the defaults are simple
890              (default (cond
891                        ((and (not given-default) (eq r 'user))
892                         (user-login-name))
893                        ;; note we need this empty string
894                        ((and (not given-default) (eq r 'protocol))
895                         "")
896                        (t given-default)))
897              ;; the prompt's default string depends on the data so far
898              (default-string (if (and default (< 0 (length default)))
899                                  (format " (default %s)" default)
900                                " (no default)"))
901              ;; the prompt should also show what's entered so far
902              (user-value (aget valist 'user))
903              (host-value (aget valist 'host))
904              (protocol-value (aget valist 'protocol))
905              (info-so-far (concat (if user-value
906                                       (format "%s@" user-value)
907                                     "[USER?]")
908                                   (if host-value
909                                       (format "%s" host-value)
910                                     "[HOST?]")
911                                   (if protocol-value
912                                       ;; this distinguishes protocol between
913                                       (if (zerop (length protocol-value))
914                                           "" ; 'entered as "no default"' vs.
915                                         (format ":%s" protocol-value)) ; given
916                                     ;; and this is when the protocol is unknown
917                                     "[PROTOCOL?]"))))
918
919         ;; now prompt if the search SPEC did not include a required key;
920         ;; take the result and put it in `data' AND store it in `valist'
921         (aput 'valist r
922               (setq data
923                     (cond
924                      ((and (null data) (eq r 'secret))
925                       ;; special case prompt for passwords
926                       (read-passwd (format "Password for %s: " info-so-far)))
927                      ((null data)
928                       (read-string
929                        (format "Enter %s for %s%s: "
930                                r info-so-far default-string)
931                        nil nil default))
932                      (t data))))
933
934         (when data
935           (setq artificial (plist-put artificial
936                                       (intern (concat ":" (symbol-name r)))
937                                       (if (eq r 'secret)
938                                           (lexical-let ((data data))
939                                             (lambda () data))
940                                         data))))
941
942         ;; when r is not an empty string...
943         (when (and (stringp data)
944                    (< 0 (length data)))
945           ;; append the key (the symbol name of r) and the value in r
946           (setq add (concat add
947                             (format "%s%s %S"
948                                     ;; prepend a space
949                                     (if (zerop (length add)) "" " ")
950                                     ;; remap auth-source tokens to netrc
951                                     (case r
952                                      ('user "login")
953                                      ('host "machine")
954                                      ('secret "password")
955                                      ('protocol "port")
956                                      (t (symbol-name r)))
957                                     ;; the value will be printed in %S format
958                                     data))))))
959
960     (with-temp-buffer
961       (when (file-exists-p file)
962         (insert-file-contents file))
963       (when auth-source-gpg-encrypt-to
964         ;; (see bug#7487) making `epa-file-encrypt-to' local to
965         ;; this buffer lets epa-file skip the key selection query
966         ;; (see the `local-variable-p' check in
967         ;; `epa-file-write-region').
968         (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
969           (make-local-variable 'epa-file-encrypt-to))
970         (if (listp auth-source-gpg-encrypt-to)
971             (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
972       (goto-char (point-max))
973
974       ;; ask AFTER we've successfully opened the file
975       (if (y-or-n-p (format "Add to file %s: line [%s]" file add))
976           (progn
977             (unless (bolp)
978               (insert "\n"))
979             (insert add "\n")
980             (write-region (point-min) (point-max) file nil 'silent)
981             (auth-source-do-debug
982              "auth-source-netrc-create: wrote 1 new line to %s"
983              file)
984             nil)
985         (list artificial)))))
986
987 ;;; Backend specific parsing: Secrets API backend
988
989 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1 :create t))
990 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1 :delete t))
991 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1))
992 ;;; (let ((auth-sources '(default))) (auth-source-search))
993 ;;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1))
994 ;;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1 :signon_realm "https://git.gnus.org/Git"))
995
996 (defun* auth-source-secrets-search (&rest
997                                     spec
998                                     &key backend create delete label
999                                     type max host user protocol
1000                                     &allow-other-keys)
1001   "Search the Secrets API; spec is like `auth-source'.
1002
1003 The :label key specifies the item's label.  It is the only key
1004 that can specify a substring.  Any :label value besides a string
1005 will allow any label.
1006
1007 All other search keys must match exactly.  If you need substring
1008 matching, do a wider search and narrow it down yourself.
1009
1010 You'll get back all the properties of the token as a plist.
1011
1012 Here's an example that looks for the first item in the 'Login'
1013 Secrets collection:
1014
1015  \(let ((auth-sources '(\"secrets:Login\")))
1016     (auth-source-search :max 1)
1017
1018 Here's another that looks for the first item in the 'Login'
1019 Secrets collection whose label contains 'gnus':
1020
1021  \(let ((auth-sources '(\"secrets:Login\")))
1022     (auth-source-search :max 1 :label \"gnus\")
1023
1024 And this one looks for the first item in the 'Login' Secrets
1025 collection that's a Google Chrome entry for the git.gnus.org site
1026 authentication tokens:
1027
1028  \(let ((auth-sources '(\"secrets:Login\")))
1029     (auth-source-search :max 1 :signon_realm \"https://git.gnus.org/Git\"))
1030 "
1031
1032   ;; TODO
1033   (assert (not create) nil
1034           "The Secrets API auth-source backend doesn't support creation yet")
1035   ;; TODO
1036   ;; (secrets-delete-item coll elt)
1037   (assert (not delete) nil
1038           "The Secrets API auth-source backend doesn't support deletion yet")
1039
1040   (let* ((coll (oref backend source))
1041          (max (or max 5000))     ; sanity check: default to stop at 5K
1042          (ignored-keys '(:create :delete :max :backend :label))
1043          (search-keys (loop for i below (length spec) by 2
1044                             unless (memq (nth i spec) ignored-keys)
1045                             collect (nth i spec)))
1046          ;; build a search spec without the ignored keys
1047          ;; if a search key is nil or t (match anything), we skip it
1048          (search-spec (apply 'append (mapcar
1049                                       (lambda (k)
1050                                         (if (or (null (plist-get spec k))
1051                                                 (eq t (plist-get spec k)))
1052                                             nil
1053                                           (list k (plist-get spec k))))
1054                               search-keys)))
1055          ;; needed keys (always including host, login, protocol, and secret)
1056          (returned-keys (mm-delete-duplicates (append
1057                                                '(:host :login :protocol :secret)
1058                                                search-keys)))
1059          (items (loop for item in (apply 'secrets-search-items coll search-spec)
1060                       unless (and (stringp label)
1061                                   (not (string-match label item)))
1062                       collect item))
1063          ;; TODO: respect max in `secrets-search-items', not after the fact
1064          (items (butlast items (- (length items) max)))
1065          ;; convert the item name to a full plist
1066          (items (mapcar (lambda (item)
1067                           (append
1068                            ;; make an entry for the secret (password) element
1069                            (list
1070                             :secret
1071                             (lexical-let ((v (secrets-get-secret coll item)))
1072                               (lambda () v)))
1073                            ;; rewrite the entry from ((k1 v1) (k2 v2)) to plist
1074                            (apply 'append
1075                                   (mapcar (lambda (entry)
1076                                             (list (car entry) (cdr entry)))
1077                                           (secrets-get-attributes coll item)))))
1078                         items))
1079          ;; ensure each item has each key in `returned-keys'
1080          (items (mapcar (lambda (plist)
1081                           (append
1082                            (apply 'append
1083                                   (mapcar (lambda (req)
1084                                             (if (plist-get plist req)
1085                                                 nil
1086                                               (list req nil)))
1087                                           returned-keys))
1088                            plist))
1089                         items)))
1090     items))
1091
1092 (defun* auth-source-secrets-create (&rest
1093                                     spec
1094                                     &key backend type max host user protocol
1095                                     &allow-other-keys)
1096   ;; TODO
1097   ;; (apply 'secrets-create-item (auth-get-source entry) name passwd spec)
1098   (debug spec))
1099
1100 ;;; older API
1101
1102 ;;; (auth-source-user-or-password '("login" "password") "imap.myhost.com" t "tzz")
1103
1104 ;; deprecate the old interface
1105 (make-obsolete 'auth-source-user-or-password
1106                'auth-source-search "Emacs 24.1")
1107 (make-obsolete 'auth-source-forget-user-or-password
1108                'auth-source-forget "Emacs 24.1")
1109
1110 (defun auth-source-user-or-password
1111   (mode host protocol &optional username create-missing delete-existing)
1112   "Find MODE (string or list of strings) matching HOST and PROTOCOL.
1113
1114 DEPRECATED in favor of `auth-source-search'!
1115
1116 USERNAME is optional and will be used as \"login\" in a search
1117 across the Secret Service API (see secrets.el) if the resulting
1118 items don't have a username.  This means that if you search for
1119 username \"joe\" and it matches an item but the item doesn't have
1120 a :user attribute, the username \"joe\" will be returned.
1121
1122 A non nil DELETE-EXISTING means deleting any matching password
1123 entry in the respective sources.  This is useful only when
1124 CREATE-MISSING is non nil as well; the intended use case is to
1125 remove wrong password entries.
1126
1127 If no matching entry is found, and CREATE-MISSING is non nil,
1128 the password will be retrieved interactively, and it will be
1129 stored in the password database which matches best (see
1130 `auth-sources').
1131
1132 MODE can be \"login\" or \"password\"."
1133   (auth-source-do-debug
1134    "auth-source-user-or-password: DEPRECATED get %s for %s (%s) + user=%s"
1135    mode host protocol username)
1136
1137   (let* ((listy (listp mode))
1138          (mode (if listy mode (list mode)))
1139          (cname (if username
1140                     (format "%s %s:%s %s" mode host protocol username)
1141                   (format "%s %s:%s" mode host protocol)))
1142          (search (list :host host :protocol protocol))
1143          (search (if username (append search (list :user username)) search))
1144          (search (if create-missing
1145                      (append search (list :create t))
1146                    search))
1147          (search (if delete-existing
1148                      (append search (list :delete t))
1149                    search))
1150          ;; (found (if (not delete-existing)
1151          ;;            (gethash cname auth-source-cache)
1152          ;;          (remhash cname auth-source-cache)
1153          ;;          nil)))
1154          (found nil))
1155     (if found
1156         (progn
1157           (auth-source-do-debug
1158            "auth-source-user-or-password: DEPRECATED cached %s=%s for %s (%s) + %s"
1159            mode
1160            ;; don't show the password
1161            (if (and (member "password" mode) t)
1162                "SECRET"
1163              found)
1164            host protocol username)
1165           found)                        ; return the found data
1166       ;; else, if not found, search with a max of 1
1167       (let ((choice (nth 0 (apply 'auth-source-search
1168                                   (append '(:max 1) search)))))
1169         (when choice
1170           (dolist (m mode)
1171             (cond
1172              ((equal "password" m)
1173               (push (if (plist-get choice :secret)
1174                       (funcall (plist-get choice :secret))
1175                     nil) found))
1176              ((equal "login" m)
1177               (push (plist-get choice :user) found)))))
1178         (setq found (nreverse found))
1179         (setq found (if listy found (car-safe found)))))
1180
1181         found))
1182
1183 (provide 'auth-source)
1184
1185 ;;; auth-source.el ends here