1 ;;; auth-source.el --- authentication sources for Gnus and Emacs
3 ;; Copyright (C) 2008-2011 Free Software Foundation, Inc.
5 ;; Author: Ted Zlatanov <tzz@lifelogs.com>
8 ;; This file is part of GNU Emacs.
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.
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.
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/>.
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.
30 ;; See the auth.info Info documentation for details.
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
42 (require 'password-cache)
46 (eval-when-compile (require 'cl))
48 (or (ignore-errors (require 'eieio))
49 ;; gnus-fallback-lib/ from gnus/lisp/gnus-fallback-lib
51 (let ((load-path (cons (expand-file-name
52 "gnus-fallback-lib/eieio"
53 (file-name-directory (locate-library "gnus")))
57 "eieio not found in `load-path' or gnus-fallback-lib/ directory.")))
59 (autoload 'secrets-create-item "secrets")
60 (autoload 'secrets-delete-item "secrets")
61 (autoload 'secrets-get-alias "secrets")
62 (autoload 'secrets-get-attributes "secrets")
63 (autoload 'secrets-get-secret "secrets")
64 (autoload 'secrets-list-collections "secrets")
65 (autoload 'secrets-search-items "secrets")
67 (autoload 'rfc2104-hash "rfc2104")
69 (defvar secrets-enabled)
71 (defgroup auth-source nil
72 "Authentication sources."
73 :version "23.1" ;; No Gnus
77 (defcustom auth-source-cache-expiry 7200
78 "How many seconds passwords are cached, or nil to disable
79 expiring. Overrides `password-cache-expiry' through a
82 :type '(choice (const :tag "Never" nil)
83 (const :tag "All Day" 86400)
84 (const :tag "2 Hours" 7200)
85 (const :tag "30 Minutes" 1800)
86 (integer :tag "Seconds")))
88 (defclass auth-source-backend ()
93 :documentation "The backend type.")
94 (source :initarg :source
97 :documentation "The backend source.")
102 :documentation "The backend host.")
107 :documentation "The backend user.")
112 :documentation "The backend protocol.")
113 (create-function :initarg :create-function
117 :documentation "The create function.")
118 (search-function :initarg :search-function
122 :documentation "The search function.")))
124 (defcustom auth-source-protocols '((imap "imap" "imaps" "143" "993")
125 (pop3 "pop3" "pop" "pop3s" "110" "995")
129 "List of authentication protocols and their names"
132 :version "23.2" ;; No Gnus
133 :type '(repeat :tag "Authentication Protocols"
134 (cons :tag "Protocol Entry"
135 (symbol :tag "Protocol")
137 (string :tag "Name")))))
139 ;;; generate all the protocols in a format Customize can use
140 ;;; TODO: generate on the fly from auth-source-protocols
141 (defconst auth-source-protocols-customize
143 (let ((p (car-safe a)))
145 :tag (upcase (symbol-name p))
147 auth-source-protocols))
149 (defvar auth-source-creation-defaults nil
150 "Defaults for creating token values. Usually let-bound.")
152 (defvar auth-source-creation-prompts nil
153 "Default prompts for token values. Usually let-bound.")
155 (make-obsolete 'auth-source-hide-passwords nil "Emacs 24.1")
157 (defcustom auth-source-save-behavior 'ask
158 "If set, auth-source will respect it for save behavior."
160 :version "23.2" ;; No Gnus
162 :tag "auth-source new token save behavior"
163 (const :tag "Always save" t)
164 (const :tag "Never save" nil)
165 (const :tag "Ask" ask)))
167 (defvar auth-source-magic "auth-source-magic ")
169 (defcustom auth-source-do-cache t
170 "Whether auth-source should cache information with `password-cache'."
172 :version "23.2" ;; No Gnus
175 (defcustom auth-source-debug nil
176 "Whether auth-source should log debug messages.
178 If the value is nil, debug messages are not logged.
180 If the value is t, debug messages are logged with `message'. In
181 that case, your authentication data will be in the clear (except
184 If the value is a function, debug messages are logged by calling
185 that function using the same arguments as `message'."
187 :version "23.2" ;; No Gnus
189 :tag "auth-source debugging mode"
190 (const :tag "Log using `message' to the *Messages* buffer" t)
191 (const :tag "Log all trivia with `message' to the *Messages* buffer"
193 (function :tag "Function that takes arguments like `message'")
194 (const :tag "Don't log anything" nil)))
196 (defcustom auth-sources '("~/.authinfo.gpg" "~/.authinfo" "~/.netrc")
197 "List of authentication sources.
199 The default will get login and password information from
200 \"~/.authinfo.gpg\", which you should set up with the EPA/EPG
201 packages to be encrypted. If that file doesn't exist, it will
202 try the unencrypted version \"~/.authinfo\" and the famous
205 See the auth.info manual for details.
207 Each entry is the authentication type with optional properties.
209 It's best to customize this with `M-x customize-variable' because the choices
210 can get pretty complex."
212 :version "24.1" ;; No Gnus
213 :type `(repeat :tag "Authentication Sources"
215 (string :tag "Just a file")
216 (const :tag "Default Secrets API Collection" 'default)
217 (const :tag "Login Secrets API Collection" "secrets:Login")
218 (const :tag "Temp Secrets API Collection" "secrets:session")
219 (list :tag "Source definition"
220 (const :format "" :value :source)
221 (choice :tag "Authentication backend choice"
222 (string :tag "Authentication Source (file)")
224 :tag "Secret Service API/KWallet/GNOME Keyring"
225 (const :format "" :value :secrets)
226 (choice :tag "Collection to use"
227 (string :tag "Collection name")
228 (const :tag "Default" 'default)
229 (const :tag "Login" "Login")
231 :tag "Temporary" "session"))))
232 (repeat :tag "Extra Parameters" :inline t
233 (choice :tag "Extra parameter"
236 (const :format "" :value :host)
237 (choice :tag "Host (machine) choice"
240 :tag "Regular expression")))
243 (const :format "" :value :port)
247 ,@auth-source-protocols-customize))
248 (list :tag "User" :inline t
249 (const :format "" :value :user)
250 (choice :tag "Personality/Username"
252 (string :tag "Name")))))))))
254 (defcustom auth-source-gpg-encrypt-to t
255 "List of recipient keys that `authinfo.gpg' encrypted to.
256 If the value is not a list, symmetric encryption will be used."
258 :version "24.1" ;; No Gnus
259 :type '(choice (const :tag "Symmetric encryption" t)
260 (repeat :tag "Recipient public keys"
261 (string :tag "Recipient public key"))))
263 ;; temp for debugging
264 ;; (unintern 'auth-source-protocols)
265 ;; (unintern 'auth-sources)
266 ;; (customize-variable 'auth-sources)
267 ;; (setq auth-sources nil)
268 ;; (format "%S" auth-sources)
269 ;; (customize-variable 'auth-source-protocols)
270 ;; (setq auth-source-protocols nil)
271 ;; (format "%S" auth-source-protocols)
272 ;; (auth-source-pick nil :host "a" :port 'imap)
273 ;; (auth-source-user-or-password "login" "imap.myhost.com" 'imap)
274 ;; (auth-source-user-or-password "password" "imap.myhost.com" 'imap)
275 ;; (auth-source-user-or-password-imap "login" "imap.myhost.com")
276 ;; (auth-source-user-or-password-imap "password" "imap.myhost.com")
277 ;; (auth-source-protocol-defaults 'imap)
279 ;; (let ((auth-source-debug 'debug)) (auth-source-do-debug "hello"))
280 ;; (let ((auth-source-debug t)) (auth-source-do-debug "hello"))
281 ;; (let ((auth-source-debug nil)) (auth-source-do-debug "hello"))
282 (defun auth-source-do-debug (&rest msg)
283 (when auth-source-debug
284 (apply 'auth-source-do-warn msg)))
286 (defun auth-source-do-trivia (&rest msg)
287 (when (or (eq auth-source-debug 'trivia)
288 (functionp auth-source-debug))
289 (apply 'auth-source-do-warn msg)))
291 (defun auth-source-do-warn (&rest msg)
293 ;; set logger to either the function in auth-source-debug or 'message
294 ;; note that it will be 'message if auth-source-debug is nil
295 (if (functionp auth-source-debug)
301 ;;; (auth-source-read-char-choice "enter choice? " '(?a ?b ?q))
302 (defun auth-source-read-char-choice (prompt choices)
303 "Read one of CHOICES by `read-char-choice', or `read-char'.
304 `dropdown-list' support is disabled because it doesn't work reliably.
305 Only one of CHOICES will be returned. The PROMPT is augmented
306 with \"[a/b/c] \" if CHOICES is '\(?a ?b ?c\)."
308 (let* ((prompt-choices
309 (apply 'concat (loop for c in choices
310 collect (format "%c/" c))))
311 (prompt-choices (concat "[" (substring prompt-choices 0 -1) "] "))
312 (full-prompt (concat prompt prompt-choices))
315 (while (not (memq k choices))
317 ((fboundp 'read-char-choice)
318 (read-char-choice full-prompt choices))
319 (t (message "%s" full-prompt)
320 (setq k (read-char))))))
323 ;; (auth-source-pick nil :host "any" :port 'imap :user "joe")
324 ;; (auth-source-pick t :host "any" :port 'imap :user "joe")
325 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
326 ;; (:source (:secrets "session") :host t :port t :user "joe")
327 ;; (:source (:secrets "Login") :host t :port t)
328 ;; (:source "~/.authinfo.gpg" :host t :port t)))
330 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
331 ;; (:source (:secrets "session") :host t :port t :user "joe")
332 ;; (:source (:secrets "Login") :host t :port t)
335 ;; (setq auth-sources '((:source "~/.authinfo.gpg" :host t :port t)))
337 ;; (auth-source-backend-parse "myfile.gpg")
338 ;; (auth-source-backend-parse 'default)
339 ;; (auth-source-backend-parse "secrets:Login")
341 (defun auth-source-backend-parse (entry)
342 "Creates an auth-source-backend from an ENTRY in `auth-sources'."
343 (auth-source-backend-parse-parameters
346 ;; take 'default and recurse to get it as a Secrets API default collection
347 ;; matching any user, host, and protocol
349 (auth-source-backend-parse '(:source (:secrets default))))
350 ;; take secrets:XYZ and recurse to get it as Secrets API collection "XYZ"
351 ;; matching any user, host, and protocol
352 ((and (stringp entry) (string-match "^secrets:\\(.+\\)" entry))
353 (auth-source-backend-parse `(:source (:secrets ,(match-string 1 entry)))))
354 ;; take just a file name and recurse to get it as a netrc file
355 ;; matching any user, host, and protocol
357 (auth-source-backend-parse `(:source ,entry)))
359 ;; a file name with parameters
360 ((stringp (plist-get entry :source))
362 (plist-get entry :source)
363 :source (plist-get entry :source)
365 :search-function 'auth-source-netrc-search
366 :create-function 'auth-source-netrc-create))
368 ;; the Secrets API. We require the package, in order to have a
369 ;; defined value for `secrets-enabled'.
371 (not (null (plist-get entry :source))) ; the source must not be nil
372 (listp (plist-get entry :source)) ; and it must be a list
373 (require 'secrets nil t) ; and we must load the Secrets API
374 secrets-enabled) ; and that API must be enabled
376 ;; the source is either the :secrets key in ENTRY or
377 ;; if that's missing or nil, it's "session"
378 (let ((source (or (plist-get (plist-get entry :source) :secrets)
381 ;; if the source is a symbol, we look for the alias named so,
382 ;; and if that alias is missing, we use "Login"
383 (when (symbolp source)
384 (setq source (or (secrets-get-alias (symbol-name source))
387 (if (featurep 'secrets)
389 (format "Secrets API (%s)" source)
392 :search-function 'auth-source-secrets-search
393 :create-function 'auth-source-secrets-create)
395 "auth-source-backend-parse: no Secrets API, ignoring spec: %S" entry)
397 (format "Ignored Secrets API (%s)" source)
404 "auth-source-backend-parse: invalid backend spec: %S" entry)
410 (defun auth-source-backend-parse-parameters (entry backend)
411 "Fills in the extra auth-source-backend parameters of ENTRY.
412 Using the plist ENTRY, get the :host, :port, and :user search
414 (let ((entry (if (stringp entry)
418 (when (setq val (plist-get entry :host))
419 (oset backend host val))
420 (when (setq val (plist-get entry :user))
421 (oset backend user val))
422 (when (setq val (plist-get entry :port))
423 (oset backend port val)))
426 ;; (mapcar 'auth-source-backend-parse auth-sources)
428 (defun* auth-source-search (&rest spec
429 &key type max host user port secret
430 require create delete
432 "Search or modify authentication backends according to SPEC.
434 This function parses `auth-sources' for matches of the SPEC
435 plist. It can optionally create or update an authentication
436 token if requested. A token is just a standard Emacs property
437 list with a :secret property that can be a function; all the
438 other properties will always hold scalar values.
440 Typically the :secret property, if present, contains a password.
442 Common search keys are :max, :host, :port, and :user. In
443 addition, :create specifies how tokens will be or created.
444 Finally, :type can specify which backend types you want to check.
446 A string value is always matched literally. A symbol is matched
447 as its string value, literally. All the SPEC values can be
448 single values (symbol or string) or lists thereof (in which case
449 any of the search terms matches).
451 :create t means to create a token if possible.
453 A new token will be created if no matching tokens were found.
454 The new token will have only the keys the backend requires. For
455 the netrc backend, for instance, that's the user, host, and
460 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
461 (A . \"default A\"))))
462 (auth-source-search :host \"mine\" :type 'netrc :max 1
463 :P \"pppp\" :Q \"qqqq\"
468 \"Search for any entry matching host 'mine' in backends of type
469 'netrc', maximum one result.
471 Create a new entry if you found none. The netrc backend will
472 automatically require host, user, and port. The host will be
473 'mine'. We prompt for the user with default 'defaultUser' and
474 for the port without a default. We will not prompt for A, Q,
475 or P. The resulting token will only have keys user, host, and
478 :create '(A B C) also means to create a token if possible.
480 The behavior is like :create t but if the list contains any
481 parameter, that parameter will be required in the resulting
482 token. The value for that parameter will be obtained from the
483 search parameters or from user input. If any queries are needed,
484 the alist `auth-source-creation-defaults' will be checked for the
485 default value. If the user, host, or port are missing, the alist
486 `auth-source-creation-prompts' will be used to look up the
487 prompts IN THAT ORDER (so the 'user prompt will be queried first,
488 then 'host, then 'port, and finally 'secret). Each prompt string
489 can use %u, %h, and %p to show the user, host, and port.
493 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
494 (A . \"default A\")))
495 (auth-source-creation-prompts
496 '((password . \"Enter IMAP password for %h:%p: \"))))
497 (auth-source-search :host '(\"nonesuch\" \"twosuch\") :type 'netrc :max 1
498 :P \"pppp\" :Q \"qqqq\"
503 \"Search for any entry matching host 'nonesuch'
504 or 'twosuch' in backends of type 'netrc', maximum one result.
506 Create a new entry if you found none. The netrc backend will
507 automatically require host, user, and port. The host will be
508 'nonesuch' and Q will be 'qqqq'. We prompt for the password
509 with the shown prompt. We will not prompt for Q. The resulting
510 token will have keys user, host, port, A, B, and Q. It will not
511 have P with any value, even though P is used in the search to
512 find only entries that have P set to 'pppp'.\"
514 When multiple values are specified in the search parameter, the
515 user is prompted for which one. So :host (X Y Z) would ask the
516 user to choose between X, Y, and Z.
518 This creation can fail if the search was not specific enough to
519 create a new token (it's up to the backend to decide that). You
520 should `catch' the backend-specific error as usual. Some
521 backends (netrc, at least) will prompt the user rather than throw
524 :require (A B C) means that only results that contain those
525 tokens will be returned. Thus for instance requiring :secret
526 will ensure that any results will actually have a :secret
529 :delete t means to delete any found entries. nil by default.
530 Use `auth-source-delete' in ELisp code instead of calling
531 `auth-source-search' directly with this parameter.
533 :type (X Y Z) will check only those backend types. 'netrc and
534 'secrets are the only ones supported right now.
536 :max N means to try to return at most N items (defaults to 1).
537 When 0 the function will return just t or nil to indicate if any
538 matches were found. More than N items may be returned, depending
539 on the search and the backend.
541 :host (X Y Z) means to match only hosts X, Y, or Z according to
542 the match rules above. Defaults to t.
544 :user (X Y Z) means to match only users X, Y, or Z according to
545 the match rules above. Defaults to t.
547 :port (P Q R) means to match only protocols P, Q, or R.
550 :K (V1 V2 V3) for any other key K will match values V1, V2, or
551 V3 (note the match rules above).
553 The return value is a list with at most :max tokens. Each token
554 is a plist with keys :backend :host :port :user, plus any other
555 keys provided by the backend (notably :secret). But note the
556 exception for :max 0, which see above.
558 The token can hold a :save-function key. If you call that, the
559 user will be prompted to save the data to the backend. You can't
560 request that this should happen right after creation, because
561 `auth-source-search' has no way of knowing if the token is
562 actually useful. So the caller must arrange to call this function.
564 The token's :secret key can hold a function. In that case you
565 must call it to obtain the actual value."
566 (let* ((backends (mapcar 'auth-source-backend-parse auth-sources))
568 (ignored-keys '(:require :create :delete :max))
569 (keys (loop for i below (length spec) by 2
570 unless (memq (nth i spec) ignored-keys)
571 collect (nth i spec)))
572 (cached (auth-source-remembered-p spec))
573 ;; note that we may have cached results but found is still nil
574 ;; (there were no results from the search)
575 (found (auth-source-recall spec))
576 filtered-backends accessor-key backend)
578 (if (and cached auth-source-do-cache)
579 (auth-source-do-debug
580 "auth-source-search: found %d CACHED results matching %S"
584 (or (eq t create) (listp create)) t
585 "Invalid auth-source :create parameter (must be t or a list): %s %s")
589 "Invalid auth-source :require parameter (must be a list): %s")
591 (setq filtered-backends (copy-sequence backends))
592 (dolist (backend backends)
594 ;; ignore invalid slots
595 (condition-case signal
596 (unless (eval `(auth-source-search-collection
598 (oref backend ,key)))
599 (setq filtered-backends (delq backend filtered-backends))
601 (invalid-slot-name))))
603 (auth-source-do-trivia
604 "auth-source-search: found %d backends matching %S"
605 (length filtered-backends) spec)
607 ;; (debug spec "filtered" filtered-backends)
608 ;; First go through all the backends without :create, so we can
610 (setq found (auth-source-search-backends filtered-backends
614 ;; create is always nil here
618 (auth-source-do-debug
619 "auth-source-search: found %d results (max %d) matching %S"
620 (length found) max spec)
622 ;; If we didn't find anything, then we allow the backend(s) to
623 ;; create the entries.
626 (setq found (auth-source-search-backends filtered-backends
632 (auth-source-do-debug
633 "auth-source-search: CREATED %d results (max %d) matching %S"
634 (length found) max spec))
636 ;; note we remember the lack of result too, if it's applicable
637 (when auth-source-do-cache
638 (auth-source-remember spec found)))
642 (defun auth-source-search-backends (backends spec max create delete require)
644 (dolist (backend backends)
645 (when (> max (length matches)) ; when we need more matches...
646 (let* ((bmatches (apply
647 (slot-value backend 'search-function)
649 ;; note we're overriding whatever the spec
650 ;; has for :require, :create, and :delete
656 (auth-source-do-trivia
657 "auth-source-search-backend: got %d (max %d) in %s:%s matching %S"
658 (length bmatches) max
659 (slot-value backend :type)
660 (slot-value backend :source)
662 (setq matches (append matches bmatches))))))
665 ;;; (auth-source-search :max 1)
666 ;;; (funcall (plist-get (nth 0 (auth-source-search :max 1)) :secret))
667 ;;; (auth-source-search :host "nonesuch" :type 'netrc :K 1)
668 ;;; (auth-source-search :host "nonesuch" :type 'secrets)
670 (defun* auth-source-delete (&rest spec
673 "Delete entries from the authentication backends according to SPEC.
674 Calls `auth-source-search' with the :delete property in SPEC set to t.
675 The backend may not actually delete the entries.
677 Returns the deleted entries."
678 (auth-source-search (plist-put spec :delete t)))
680 (defun auth-source-search-collection (collection value)
681 "Returns t is VALUE is t or COLLECTION is t or contains VALUE."
682 (when (and (atom collection) (not (eq t collection)))
683 (setq collection (list collection)))
685 ;; (debug :collection collection :value value)
686 (or (eq collection t)
688 (equal collection value)
689 (member value collection)))
691 (defun auth-source-forget-all-cached ()
692 "Forget all cached auth-source data."
694 (loop for sym being the symbols of password-data
695 ;; when the symbol name starts with auth-source-magic
696 when (string-match (concat "^" auth-source-magic)
699 do (password-cache-remove (symbol-name sym))))
701 (defun auth-source-remember (spec found)
702 "Remember FOUND search results for SPEC."
703 (let ((password-cache-expiry auth-source-cache-expiry))
705 (concat auth-source-magic (format "%S" spec)) found)))
707 (defun auth-source-recall (spec)
708 "Recall FOUND search results for SPEC."
709 (password-read-from-cache
710 (concat auth-source-magic (format "%S" spec))))
712 (defun auth-source-remembered-p (spec)
713 "Check if SPEC is remembered."
715 (concat auth-source-magic (format "%S" spec))))
717 (defun auth-source-forget (spec)
718 "Forget any cached data matching SPEC exactly.
720 This is the same SPEC you passed to `auth-source-search'.
721 Returns t or nil for forgotten or not found."
722 (password-cache-remove (concat auth-source-magic (format "%S" spec))))
724 ;;; (loop for sym being the symbols of password-data when (string-match (concat "^" auth-source-magic) (symbol-name sym)) collect (symbol-name sym))
726 ;;; (auth-source-remember '(:host "wedd") '(4 5 6))
727 ;;; (auth-source-remembered-p '(:host "wedd"))
728 ;;; (auth-source-remember '(:host "xedd") '(1 2 3))
729 ;;; (auth-source-remembered-p '(:host "xedd"))
730 ;;; (auth-source-remembered-p '(:host "zedd"))
731 ;;; (auth-source-recall '(:host "xedd"))
732 ;;; (auth-source-recall '(:host t))
733 ;;; (auth-source-forget+ :host t)
735 (defun* auth-source-forget+ (&rest spec &allow-other-keys)
736 "Forget any cached data matching SPEC. Returns forgotten count.
738 This is not a full `auth-source-search' spec but works similarly.
739 For instance, \(:host \"myhost\" \"yourhost\") would find all the
740 cached data that was found with a search for those two hosts,
741 while \(:host t) would find all host entries."
744 (loop for sym being the symbols of password-data
745 ;; when the symbol name matches with auth-source-magic
746 when (and (setq sname (symbol-name sym))
747 (string-match (concat "^" auth-source-magic "\\(.+\\)")
749 ;; and the spec matches what was stored in the cache
750 (auth-source-specmatchp spec (read (match-string 1 sname))))
753 (password-cache-remove sname)
757 (defun auth-source-specmatchp (spec stored)
758 (let ((keys (loop for i below (length spec) by 2
759 collect (nth i spec))))
762 (unless (auth-source-search-collection (plist-get stored key)
763 (plist-get spec key))
767 ;;; (auth-source-pick-first-password :host "z.lifelogs.com")
768 ;;; (auth-source-pick-first-password :port "imap")
769 (defun auth-source-pick-first-password (&rest spec)
770 "Pick the first secret found from applying SPEC to `auth-source-search'."
771 (let* ((result (nth 0 (apply 'auth-source-search (plist-put spec :max 1))))
772 (secret (plist-get result :secret)))
774 (if (functionp secret)
778 ;; (auth-source-format-prompt "test %u %h %p" '((?u "user") (?h "host")))
779 (defun auth-source-format-prompt (prompt alist)
780 "Format PROMPT using %x (for any character x) specifiers in ALIST."
782 (let ((c (nth 0 cell))
785 (setq prompt (replace-regexp-in-string (format "%%%c" c)
790 (defun auth-source-ensure-strings (values)
791 (unless (listp values)
792 (setq values (list values)))
793 (mapcar (lambda (value)
799 ;;; Backend specific parsing: netrc/authinfo backend
801 (defvar auth-source-netrc-cache nil)
803 ;;; (auth-source-netrc-parse "~/.authinfo.gpg")
804 (defun* auth-source-netrc-parse (&rest
806 &key file max host user port delete require
808 "Parse FILE and return a list of all entries in the file.
809 Note that the MAX parameter is used so we can exit the parse early."
811 ;; We got already parsed contents; just return it.
813 (when (file-exists-p file)
814 (setq port (auth-source-ensure-strings port))
816 (let* ((tokens '("machine" "host" "default" "login" "user"
817 "password" "account" "macdef" "force"
819 (max (or max 5000)) ; sanity check: default to stop at 5K
821 (cached (cdr-safe (assoc file auth-source-netrc-cache)))
822 (cached-mtime (plist-get cached :mtime))
823 (cached-secrets (plist-get cached :secret))
824 alist elem result pair)
826 (if (and (functionp cached-secrets)
828 (nth 5 (file-attributes file))))
830 (auth-source-do-trivia
831 "auth-source-netrc-parse: using CACHED file data for %s"
833 (insert (funcall cached-secrets)))
834 (insert-file-contents file)
835 ;; cache all netrc files (used to be just .gpg files)
836 ;; Store the contents of the file heavily encrypted in memory.
837 ;; (note for the irony-impaired: they are just obfuscated)
838 (aput 'auth-source-netrc-cache file
839 (list :mtime (nth 5 (file-attributes file))
840 :secret (lexical-let ((v (rot13-string
841 (base64-encode-string
843 (lambda () (base64-decode-string
844 (rot13-string v)))))))
845 (goto-char (point-min))
846 ;; Go through the file, line by line.
847 (while (and (not (eobp))
850 (narrow-to-region (point) (point-at-eol))
851 ;; For each line, get the tokens and values.
853 (skip-chars-forward "\t ")
854 ;; Skip lines that begin with a "#".
855 (if (eq (char-after) ?#)
856 (goto-char (point-max))
859 (if (= (following-char) ?\")
860 (read (current-buffer))
862 (point) (progn (skip-chars-forward "^\t ")
865 ((equal elem "macdef")
866 ;; We skip past the macro definition.
868 (while (and (zerop (forward-line 1))
870 (narrow-to-region (point) (point)))
871 ((member elem tokens)
872 ;; Tokens that don't have a following value are ignored,
874 (when (and pair (or (cdr pair)
875 (equal (car pair) "default")))
877 (setq pair (list elem)))
879 ;; Values that haven't got a preceding token are ignored.
883 (setq pair nil)))))))
887 (auth-source-search-collection
890 (aget alist "machine")
893 (auth-source-search-collection
897 (aget alist "account")
900 (auth-source-search-collection
904 (aget alist "protocol")
907 ;; the required list of keys is nil, or
909 ;; every element of require is in the normalized list
910 (let ((normalized (nth 0 (auth-source-netrc-normalize
912 (loop for req in require
913 always (plist-get normalized req)))))
915 (push (nreverse alist) result)
916 ;; to delete a line, we just comment it out
918 (goto-char (point-min))
927 (when auth-source-gpg-encrypt-to
928 ;; (see bug#7487) making `epa-file-encrypt-to' local to
929 ;; this buffer lets epa-file skip the key selection query
930 ;; (see the `local-variable-p' check in
931 ;; `epa-file-write-region').
932 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
933 (make-local-variable 'epa-file-encrypt-to))
934 (if (listp auth-source-gpg-encrypt-to)
935 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
937 ;; ask AFTER we've successfully opened the file
938 (when (y-or-n-p (format "Save file %s? (%d deletions)"
940 (write-region (point-min) (point-max) file nil 'silent)
941 (auth-source-do-debug
942 "auth-source-netrc-parse: modified %d lines in %s"
945 (nreverse result))))))
947 (defun auth-source-netrc-normalize (alist)
948 (mapcar (lambda (entry)
950 (while (setq item (pop entry))
955 (setq k (cond ((member k '("machine")) "host")
956 ((member k '("login" "account")) "user")
957 ((member k '("protocol")) "port")
958 ((member k '("password")) "secret")
961 ;; send back the secret in a function (lexical binding)
962 (when (equal k "secret")
963 (setq v (lexical-let ((v v))
966 (setq ret (plist-put ret
967 (intern (concat ":" k))
973 ;;; (setq secret (plist-get (nth 0 (auth-source-search :host t :type 'netrc :K 1 :max 1)) :secret))
976 (defun* auth-source-netrc-search (&rest
978 &key backend require create delete
979 type max host user port
981 "Given a property list SPEC, return search matches from the :backend.
982 See `auth-source-search' for details on SPEC."
983 ;; just in case, check that the type is correct (null or same as the backend)
984 (assert (or (null type) (eq type (oref backend type)))
985 t "Invalid netrc search: %s %s")
987 (let ((results (auth-source-netrc-normalize
988 (auth-source-netrc-parse
992 :file (oref backend source)
995 :port (or port t)))))
997 ;; if we need to create an entry AND none were found to match
1001 ;; create based on the spec and record the value
1003 ;; if the user did not want to create the entry
1004 ;; in the file, it will be returned
1005 (apply (slot-value backend 'create-function) spec)
1006 ;; if not, we do the search again without :create
1007 ;; to get the updated data.
1009 ;; the result will be returned, even if the search fails
1010 (apply 'auth-source-netrc-search
1011 (plist-put spec :create nil)))))
1014 (defun auth-source-netrc-element-or-first (v)
1019 ;;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t)
1020 ;;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t :create-extra-keys '((A "default A") (B)))
1022 (defun* auth-source-netrc-create (&rest spec
1024 secret host user port create
1026 (let* ((base-required '(host user port secret))
1027 ;; we know (because of an assertion in auth-source-search) that the
1028 ;; :create parameter is either t or a list (which includes nil)
1029 (create-extra (if (eq t create) nil create))
1030 (required (append base-required create-extra))
1031 (file (oref backend source))
1033 ;; `valist' is an alist
1035 ;; `artificial' will be returned if no creation is needed
1038 ;; only for base required elements (defined as function parameters):
1039 ;; fill in the valist with whatever data we may have from the search
1040 ;; we complete the first value if it's a list and use the value otherwise
1041 (dolist (br base-required)
1042 (when (symbol-value br)
1043 (let ((br-choice (cond
1044 ;; all-accepting choice (predicate is t)
1045 ((eq t (symbol-value br)) nil)
1046 ;; just the value otherwise
1047 (t (symbol-value br)))))
1049 (aput 'valist br br-choice)))))
1051 ;; for extra required elements, see if the spec includes a value for them
1052 (dolist (er create-extra)
1053 (let ((name (concat ":" (symbol-name er)))
1054 (keys (loop for i below (length spec) by 2
1055 collect (nth i spec))))
1057 (when (equal (symbol-name k) name)
1058 (aput 'valist er (plist-get spec k))))))
1060 ;; for each required element
1061 (dolist (r required)
1062 (let* ((data (aget valist r))
1063 ;; take the first element if the data is a list
1064 (data (auth-source-netrc-element-or-first data))
1065 ;; this is the default to be offered
1066 (given-default (aget auth-source-creation-defaults r))
1067 ;; the default supplementals are simple:
1068 ;; for the user, try `given-default' and then (user-login-name);
1069 ;; otherwise take `given-default'
1071 ((and (not given-default) (eq r 'user))
1074 (printable-defaults (list
1077 (auth-source-netrc-element-or-first
1078 (aget valist 'user))
1079 (plist-get artificial :user)
1083 (auth-source-netrc-element-or-first
1084 (aget valist 'host))
1085 (plist-get artificial :host)
1089 (auth-source-netrc-element-or-first
1090 (aget valist 'port))
1091 (plist-get artificial :port)
1093 (prompt (or (aget auth-source-creation-prompts r)
1095 (secret "%p password for %u@%h: ")
1096 (user "%p user name for %h: ")
1097 (host "%p host name for user %u: ")
1098 (port "%p port for %u@%h: "))
1099 (format "Enter %s (%%u@%%h:%%p): " r)))
1100 (prompt (auth-source-format-prompt
1102 `((?u ,(aget printable-defaults 'user))
1103 (?h ,(aget printable-defaults 'host))
1104 (?p ,(aget printable-defaults 'port))))))
1106 ;; store the data, prompting for the password if needed
1109 ((and (null data) (eq r 'secret))
1110 ;; special case prompt for passwords
1111 (read-passwd prompt))
1113 (read-string prompt nil nil default))
1114 (t (or data default))))
1117 (setq artificial (plist-put artificial
1118 (intern (concat ":" (symbol-name r)))
1120 (lexical-let ((data data))
1124 ;; when r is not an empty string...
1125 (when (and (stringp data)
1126 (< 0 (length data)))
1127 ;; this function is not strictly necessary but I think it
1128 ;; makes the code clearer -tzz
1129 (let ((printer (lambda ()
1130 ;; append the key (the symbol name of r)
1131 ;; and the value in r
1134 (if (zerop (length add)) "" " ")
1135 ;; remap auth-source tokens to netrc
1139 ('secret "password")
1140 ('port "port") ; redundant but clearer
1141 (t (symbol-name r)))
1142 ;; the value will be printed in %S format
1144 (setq add (concat add (funcall printer)))))))
1149 (lexical-let ((file file)
1151 (lambda () (auth-source-netrc-saver file add))))
1155 ;;(funcall (plist-get (nth 0 (auth-source-search :host '("nonesuch2") :user "tzz" :port "imap" :create t :max 1)) :save-function))
1156 (defun auth-source-netrc-saver (file add)
1157 "Save a line ADD in FILE, prompting along the way.
1158 Respects `auth-source-save-behavior'. Uses
1159 `auth-source-netrc-cache' to avoid prompting more than once."
1160 (let* ((key (format "%s %s" file (rfc2104-hash 'md5 64 16 file add)))
1161 (cached (assoc key auth-source-netrc-cache)))
1164 (auth-source-do-trivia
1165 "auth-source-netrc-saver: found previous run for key %s, returning"
1168 (when (file-exists-p file)
1169 (insert-file-contents file))
1170 (when auth-source-gpg-encrypt-to
1171 ;; (see bug#7487) making `epa-file-encrypt-to' local to
1172 ;; this buffer lets epa-file skip the key selection query
1173 ;; (see the `local-variable-p' check in
1174 ;; `epa-file-write-region').
1175 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
1176 (make-local-variable 'epa-file-encrypt-to))
1177 (if (listp auth-source-gpg-encrypt-to)
1178 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
1179 ;; we want the new data to be found first, so insert at beginning
1180 (goto-char (point-min))
1182 ;; ask AFTER we've successfully opened the file
1183 (let ((prompt (format "Save auth info to file %s? " file))
1184 (done (not (eq auth-source-save-behavior 'ask)))
1185 (bufname "*auth-source Help*")
1188 (setq k (auth-source-read-char-choice prompt '(?y ?n ?N ?e ??)))
1192 (with-output-to-temp-buffer bufname
1194 (concat "(y)es, save\n"
1195 "(n)o but use the info\n"
1196 "(N)o and don't ask to save again\n"
1198 "(?) for help as you can see.\n"))
1199 (set-buffer standard-output)
1205 auth-source-save-behavior nil))
1206 (?e (setq add (read-string "Line to add: " add)))
1209 (when (get-buffer-window bufname)
1210 (delete-window (get-buffer-window bufname)))
1212 ;; make sure the info is not saved
1213 (when (null auth-source-save-behavior)
1216 (when (< 0 (length add))
1221 (write-region (point-min) (point-max) file nil 'silent)
1222 (auth-source-do-debug
1223 "auth-source-netrc-create: wrote 1 new line to %s"
1225 (message "Saved new authentication information to %s" file)
1227 (aput 'auth-source-netrc-cache key "ran"))))
1229 ;;; Backend specific parsing: Secrets API backend
1231 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1 :create t))
1232 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1 :delete t))
1233 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1))
1234 ;;; (let ((auth-sources '(default))) (auth-source-search))
1235 ;;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1))
1236 ;;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1 :signon_realm "https://git.gnus.org/Git"))
1238 (defun* auth-source-secrets-search (&rest
1240 &key backend create delete label
1241 type max host user port
1243 "Search the Secrets API; spec is like `auth-source'.
1245 The :label key specifies the item's label. It is the only key
1246 that can specify a substring. Any :label value besides a string
1247 will allow any label.
1249 All other search keys must match exactly. If you need substring
1250 matching, do a wider search and narrow it down yourself.
1252 You'll get back all the properties of the token as a plist.
1254 Here's an example that looks for the first item in the 'Login'
1257 \(let ((auth-sources '(\"secrets:Login\")))
1258 (auth-source-search :max 1)
1260 Here's another that looks for the first item in the 'Login'
1261 Secrets collection whose label contains 'gnus':
1263 \(let ((auth-sources '(\"secrets:Login\")))
1264 (auth-source-search :max 1 :label \"gnus\")
1266 And this one looks for the first item in the 'Login' Secrets
1267 collection that's a Google Chrome entry for the git.gnus.org site
1268 authentication tokens:
1270 \(let ((auth-sources '(\"secrets:Login\")))
1271 (auth-source-search :max 1 :signon_realm \"https://git.gnus.org/Git\"))
1275 (assert (not create) nil
1276 "The Secrets API auth-source backend doesn't support creation yet")
1278 ;; (secrets-delete-item coll elt)
1279 (assert (not delete) nil
1280 "The Secrets API auth-source backend doesn't support deletion yet")
1282 (let* ((coll (oref backend source))
1283 (max (or max 5000)) ; sanity check: default to stop at 5K
1284 (ignored-keys '(:create :delete :max :backend :label))
1285 (search-keys (loop for i below (length spec) by 2
1286 unless (memq (nth i spec) ignored-keys)
1287 collect (nth i spec)))
1288 ;; build a search spec without the ignored keys
1289 ;; if a search key is nil or t (match anything), we skip it
1290 (search-spec (apply 'append (mapcar
1292 (if (or (null (plist-get spec k))
1293 (eq t (plist-get spec k)))
1295 (list k (plist-get spec k))))
1297 ;; needed keys (always including host, login, port, and secret)
1298 (returned-keys (mm-delete-duplicates (append
1299 '(:host :login :port :secret)
1301 (items (loop for item in (apply 'secrets-search-items coll search-spec)
1302 unless (and (stringp label)
1303 (not (string-match label item)))
1305 ;; TODO: respect max in `secrets-search-items', not after the fact
1306 (items (butlast items (- (length items) max)))
1307 ;; convert the item name to a full plist
1308 (items (mapcar (lambda (item)
1310 ;; make an entry for the secret (password) element
1313 (lexical-let ((v (secrets-get-secret coll item)))
1315 ;; rewrite the entry from ((k1 v1) (k2 v2)) to plist
1317 (mapcar (lambda (entry)
1318 (list (car entry) (cdr entry)))
1319 (secrets-get-attributes coll item)))))
1321 ;; ensure each item has each key in `returned-keys'
1322 (items (mapcar (lambda (plist)
1325 (mapcar (lambda (req)
1326 (if (plist-get plist req)
1334 (defun* auth-source-secrets-create (&rest
1336 &key backend type max host user port
1339 ;; (apply 'secrets-create-item (auth-get-source entry) name passwd spec)
1344 ;;; (auth-source-user-or-password '("login" "password") "imap.myhost.com" t "tzz")
1346 ;; deprecate the old interface
1347 (make-obsolete 'auth-source-user-or-password
1348 'auth-source-search "Emacs 24.1")
1349 (make-obsolete 'auth-source-forget-user-or-password
1350 'auth-source-forget "Emacs 24.1")
1352 (defun auth-source-user-or-password
1353 (mode host port &optional username create-missing delete-existing)
1354 "Find MODE (string or list of strings) matching HOST and PORT.
1356 DEPRECATED in favor of `auth-source-search'!
1358 USERNAME is optional and will be used as \"login\" in a search
1359 across the Secret Service API (see secrets.el) if the resulting
1360 items don't have a username. This means that if you search for
1361 username \"joe\" and it matches an item but the item doesn't have
1362 a :user attribute, the username \"joe\" will be returned.
1364 A non nil DELETE-EXISTING means deleting any matching password
1365 entry in the respective sources. This is useful only when
1366 CREATE-MISSING is non nil as well; the intended use case is to
1367 remove wrong password entries.
1369 If no matching entry is found, and CREATE-MISSING is non nil,
1370 the password will be retrieved interactively, and it will be
1371 stored in the password database which matches best (see
1374 MODE can be \"login\" or \"password\"."
1375 (auth-source-do-debug
1376 "auth-source-user-or-password: DEPRECATED get %s for %s (%s) + user=%s"
1377 mode host port username)
1379 (let* ((listy (listp mode))
1380 (mode (if listy mode (list mode)))
1382 (format "%s %s:%s %s" mode host port username)
1383 (format "%s %s:%s" mode host port)))
1384 (search (list :host host :port port))
1385 (search (if username (append search (list :user username)) search))
1386 (search (if create-missing
1387 (append search (list :create t))
1389 (search (if delete-existing
1390 (append search (list :delete t))
1392 ;; (found (if (not delete-existing)
1393 ;; (gethash cname auth-source-cache)
1394 ;; (remhash cname auth-source-cache)
1399 (auth-source-do-debug
1400 "auth-source-user-or-password: DEPRECATED cached %s=%s for %s (%s) + %s"
1402 ;; don't show the password
1403 (if (and (member "password" mode) t)
1407 found) ; return the found data
1408 ;; else, if not found, search with a max of 1
1409 (let ((choice (nth 0 (apply 'auth-source-search
1410 (append '(:max 1) search)))))
1414 ((equal "password" m)
1415 (push (if (plist-get choice :secret)
1416 (funcall (plist-get choice :secret))
1419 (push (plist-get choice :user) found)))))
1420 (setq found (nreverse found))
1421 (setq found (if listy found (car-safe found)))))
1425 (provide 'auth-source)
1427 ;;; auth-source.el ends here